Guice相当于Spring的@Autowire实例列表 [英] Guice equivalent of Spring's @Autowire list of instances
问题描述
在春季,当我这样做:
@Autowire
List<MyInterface> myInterfaces;
然后该列表将由实现MyInterface
的所有bean填充.我不必创建List<MyInterface>
类型的bean.
then this list will get populated by all beans which implement MyInterface
. I didn't have to create bean of type List<MyInterface>
.
我正在Google Guice中寻找这种行为.
I'm looking for such behaviour in Google Guice.
到目前为止,我去了:
Multibinder<MyInterface> myInterfaceBinder = MultiBinder.newSetBinder(binder(), MyInterface.class);
现在,如果我有一个实现MyInterface
的bean并绑定了它,请通过以下方式进行说明:
Now if I have a bean which implements MyInterface
and I bind it, say via:
bind(MyInterfaceImpl.class).asEagerSingleton();
它不会包含在我的多功能装订器中.我需要添加:
it won't be included in my multibinder. I need to add:
myInterfaceBinder.addBinding.to(MyInterfaceImpl.class);
这比Spring所提供的更为复杂.所以我很想知道我是否以错误的方式使用它.那么有没有更简单的方法来实现这一目标?
This is somewhat more complicated than what Spring offers. So I was wonmdering whether I'm not using it in wrong way. So is there easier way of achieving this?
推荐答案
我自己还没有那样使用它,但是根据Guice的API文档,我认为您应该能够编写的内容不超过此内容一次:
I haven't used it that way myself, yet, but according to Guice's API documentation, I think you should be able to write something not much more than this once:
bindListener(Matchers.subclassesOf(MyInterface.class), new TypeListener() {
public <I> void hear(TypeLiteral<I> typeLiteral,
TypeEncounter<I> typeEncounter) {
myInterfaceBinder.addBinding().to(typeLiteral);
}
}
然后,当您通过绑定实现时
Then, when you bind an implementation via
bind(MyInterfaceImpl.class).asEagerSingleton();
它应该被自动添加到您的多粘合剂中.
it should be added to your multibinder automatically.
这篇关于Guice相当于Spring的@Autowire实例列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!