Guice, Groovy, and Static Injection

336 views
Skip to first unread message

Christopher Piggott

unread,
Feb 19, 2011, 8:02:22 PM2/19/11
to google-guice
Hi,

I want to inject things into Groovy scripts, but would prefer to
create them without groovy-guice if possible. My java code looks like
this:

final Class groovyClass = gcl.parseClass(someFile);

Injector childInjector =
mainInjector.createChildInjector(new AbstractModule() {

@Override
protected void configure() {
requestStaticInjection(groovyClass);
}
});


String[] args = {};
Class[] argTypes = {args.getClass()};
Object passedArgv[] = {args};
Method m = groovyClass.getMethod("main", argTypes);
m.invoke(groovyClass, passedArgv);


my groovy looks like:

@Inject Screen screen;

if(screen != null) {
println "We have one!"
} else {
println "There is no screen :("
}

I think this should work ... I believe that Screen is implicitly
static and that requestStaticInjection should cause it to be injected
at the time I create the child injector. However, it doesn't seem to
be working.

I realize this is stuck somewhere between a groovy question and a
guice question but I think it's closer to guice since the groovy class
is just a class (once compiled by the guts underneath
GroovyClassLoader).

What's wrong?

--Chris

Brian Pontarelli

unread,
Feb 20, 2011, 5:09:26 PM2/20/11
to google...@googlegroups.com
What is happening is that all variables defined in a script are local to the scripts run() method. Therefore, your "@Inject Screen screen" will never get injected. Essentially, that script compiles to this:

public class MyScript extends GroovyScript {
public void run(String... args) {
@Inject Screen screen;

if(screen != null) {
println "We have one!"
} else {
println "There is no screen :("
}
}
}

There are a couple of ways to get around this:

1) You can use the new annotations in Groovy 1.8 that make script variables members or static. I think these annotations are part of Groovy 1.8, but don't take my word on that. I think these look like this:

@Member @Inject Screen screen
@Static @Inject Screen screen

2) You can perform some AST to move the variables from the run() method to the class as an instance variable or static variable

I went with #2 since I didn't have access to the annotations.

-bp

> --
> You received this message because you are subscribed to the Google Groups "google-guice" group.
> To post to this group, send email to google...@googlegroups.com.
> To unsubscribe from this group, send email to google-guice...@googlegroups.com.
> For more options, visit this group at http://groups.google.com/group/google-guice?hl=en.
>

Reply all
Reply to author
Forward
0 new messages