春天的时候我这样做:
@Autowire
List<MyInterface> myInterfaces;
Run Code Online (Sandbox Code Playgroud)
然后这个列表将被所有实现的bean填充MyInterface.我没有创建类型的bean List<MyInterface>.
我在Google Guice中寻找此类行为.
Sofar我去了:
Multibinder<MyInterface> myInterfaceBinder = MultiBinder.newSetBinder(binder(), MyInterface.class);
Run Code Online (Sandbox Code Playgroud)
现在如果我有一个实现MyInterface并绑定它的bean ,请通过:
bind(MyInterfaceImpl.class).asEagerSingleton();
Run Code Online (Sandbox Code Playgroud)
它不会包含在我的multibinder中.我需要添加:
myInterfaceBinder.addBinding.to(MyInterfaceImpl.class);
Run Code Online (Sandbox Code Playgroud)
这比Spring提供的要复杂一些.所以我很惊讶我是不是以错误的方式使用它.那么有更简单的方法来实现这一目标吗?
小智 2
我自己还没有这样使用过它,但是根据 Guice 的 API 文档,我认为你应该能够编写比这一次更多的东西:
bindListener(Matchers.subclassesOf(MyInterface.class), new TypeListener() {
public <I> void hear(TypeLiteral<I> typeLiteral,
TypeEncounter<I> typeEncounter) {
myInterfaceBinder.addBinding().to(typeLiteral);
}
}
Run Code Online (Sandbox Code Playgroud)
然后,当您通过绑定实现时
bind(MyInterfaceImpl.class).asEagerSingleton();
Run Code Online (Sandbox Code Playgroud)
它应该会自动添加到您的多重绑定器中。
| 归档时间: |
|
| 查看次数: |
1778 次 |
| 最近记录: |