guice
guice copied to clipboard
Support static JSR-250 injection
OK, I'm not really sure where this would be implemented yet (or if it's even possible). Would it be possible to make the @Resource
annotation work with requestStaticInjection
? Here's a very Java-esque Groovy example
@Grab(group='com.google.inject', module='guice', version='3.0')
@Grab(group='com.mycila.guice.extensions', module='mycila-guice-jsr250', version='3.6.ga')
import javax.annotation.Resource;
import javax.inject.Inject;
import javax.inject.Named;
import com.google.inject.name.Names;
import com.google.inject.AbstractModule;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.Stage;
import com.mycila.guice.ext.jsr250.Jsr250Module;
import com.mycila.guice.ext.closeable.CloseableModule;
public class Main {
public static void main(String[] args) {
Bean bean = new Bean();
System.out.println("thing before injection='"+StaticBag.thing+"'");
Injector injector = Guice.createInjector(Stage.PRODUCTION, new Jsr250Module(), new CloseableModule(), new AbstractModule() {
@Override
protected void configure() {
requestStaticInjection(StaticBag.class);
bind(String.class).annotatedWith(Names.named("thing")).toInstance("some string");
}
});
injector.injectMembers(bean);
System.out.println("thing after injection='"+StaticBag.thing+"'");
}
public static class Bean {}
public static class StaticBag {
// doesn't work
@Resource
// works
// @Inject @Named("thing")
public static String thing;
}
}
One workaround is to include the binding to the static class (bind(StaticBag.class).toInstance(new StaticBag());
) so that a reference to the statically injected class gets into the module, but this is a bit clunky.
Please send a PR :-)