我有以下使用 Guice 绑定的代码:
public class MyApplication {
public static void main(String[] args) {
Guice.createInjector(new AbstractModule() {
@Override
protected void configure() {
bind(Foo.class).annotatedWith(Names.named("first")).toInstance(new Foo("firstFoo"));
bind(Foo.class).annotatedWith(Names.named("second")).toInstance(new Foo("secondFoo"));
bind(Bar.class).to(BarImpl.class);
bind(MyApplication.class).asEagerSingleton();
}
});
}
private @Named("first") Bar first;
private @Named("second") Bar second;
static @Value class Foo { String name; }
static interface Bar {}
static class BarImpl implements Bar {
@Inject @Named Foo foo;
}
}
我正在尝试为注入到我的应用程序中Bar
的两个命名 s 获取一个对象。Foo
基本上,它应该以某种方式将@Named
onFoo
与 on连接起来Bar
。我尝试了几种解决方案,从穿上@Named
一切到编写自定义Provider
. 后者不起作用,因为我无权访问@Named
提供程序中注释的值。我认为解决方案在某处bind(Bar.class).to(BarImpl.class);
,告诉它记住@Named
注释的值。
我的问题是,这有可能吗?如果有,怎么做?