在 Spring 的时候:
@Autowire
List<MyInterface> myInterfaces;
然后这个列表将被所有实现MyInterface
的bean填充.我不必创建 List<MyInterface>
类型的 bean .
我正在 Google Guice 中寻找此类行为。
目前我使用的是:
Multibinder<MyInterface> myInterfaceBinder = MultiBinder.newSetBinder(binder(), MyInterface.class);
现在如果我有一个实现 MyInterface
的 bean我绑定(bind)它,说通过:
bind(MyInterfaceImpl.class).asEagerSingleton();
它不会包含在我的 multibinder 中。我需要添加:
myInterfaceBinder.addBinding.to(MyInterfaceImpl.class);
这比 Spring 提供的要复杂一些。所以我想知道我是否没有以错误的方式使用它。那么有没有更简单的方法来实现这一点?
最佳答案
我自己还没有那样使用过它,但是根据 Guice 的 API 文档,我认为您应该能够编写的内容不超过这一次:
bindListener(Matchers.subclassesOf(MyInterface.class), new TypeListener() {
public <I> void hear(TypeLiteral<I> typeLiteral,
TypeEncounter<I> typeEncounter) {
myInterfaceBinder.addBinding().to(typeLiteral);
}
}
然后,当您通过
绑定(bind)实现时bind(MyInterfaceImpl.class).asEagerSingleton();
它应该会自动添加到您的 multibinder 中。
关于java - Guice 相当于 Spring 的 @Autowire 实例列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25506133/