我知道我正在挖掘一个旧线程,但我想与其他人分享我的发现。
很久以前就请求过此功能,但尚不支持。最合适的注释是JSR 250的@Resource注释。@jan-galinski 没有错,但是已经有第三方解决方案已经为您完成了这项工作。
GuiceyFruit添加了这个功能,但它似乎被放弃了(并非所有功能都适用于 Guice 3)。尽管如此,这里有一个如何做到这一点的例子
@GrabResolver(name='GuiceyFruit', root='http://guiceyfruit.googlecode.com/svn/repo/releases')
@Grab(group='org.guiceyfruit', module='guiceyfruit-spring', version='2.0')
@Grab(group='com.google.inject', module='guice', version='3.0')
import javax.annotation.Resource;
import com.google.inject.name.Names;
import com.google.inject.AbstractModule;
import com.google.inject.Guice;
import org.guiceyfruit.spring.SpringModule;
public class Main {
public static void main(String[] args) {
Box box = new Box();
System.out.println("thingOne before injection='"+box.thingOne+"'");
System.out.println("thingTwo before injection='"+box.thingTwo+"'");
Guice.createInjector(new SpringModule(), new AbstractModule() {
@Override
protected void configure() {
bind(String.class).annotatedWith(Names.named("thingOne")).toInstance("THING ONE");
bind(String.class).annotatedWith(Names.named("thingTwo")).toInstance("THING TWO");
}
}).injectMembers(box);
System.out.println("thingOne after injection='"+box.thingOne+"'");
System.out.println("thingTwo after injection='"+box.thingTwo+"'");
}
public static class Box {
@Resource public String thingOne;
@Resource public String thingTwo;
}
}
mycila Guice Extensions是另一种选择(我会推荐它,因为它仍然得到维护并提供更好的模块化)。我已请求添加此功能,因此应该很快就会提供。一旦它是,这里是如何使用它:
@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 com.google.inject.name.Names;
import com.google.inject.AbstractModule;
import com.google.inject.Guice;
import com.mycila.guice.ext.jsr250.Jsr250Module;
import com.mycila.guice.ext.closeable.CloseableModule;
public class Main {
public static void main(String[] args) {
Box box = new Box();
System.out.println("thingOne before injection='"+box.thingOne+"'");
System.out.println("thingTwo before injection='"+box.thingTwo+"'");
Guice.createInjector(new Jsr250Module(), new CloseableModule(), new AbstractModule() {
@Override
protected void configure() {
bind(String.class).annotatedWith(Names.named("thingOne")).toInstance("THING ONE");
bind(String.class).annotatedWith(Names.named("thingTwo")).toInstance("THING TWO");
}
}).injectMembers(box);
System.out.println("thingOne after injection='"+box.thingOne+"'");
System.out.println("thingTwo after injection='"+box.thingTwo+"'");
}
public static class Box {
@Resource public String thingOne;
@Resource public String thingTwo;
}
}
最后,Netflix 的Governator还支持 @Resource 连接,但连接起来有点笨拙。这个单元测试看起来是我能找到的最好的例子。