Java 用Guice注入类集合
我正在尝试使用Google Guice 2.0注入东西,我有以下结构:Java 用Guice注入类集合,java,guice,Java,Guice,我正在尝试使用Google Guice 2.0注入东西,我有以下结构: FooAction implements Action BarAction implements Action 然后,我有一个具有以下构造函数的ActionLibrary: ActionLibrary (List<Action> theActions) 动作库(列出动作) 当我从Guice请求ActionLibrary的实例时,我希望Guice识别两个注册的操作类(FooAction、BarAction),
FooAction implements Action
BarAction implements Action
然后,我有一个具有以下构造函数的ActionLibrary:
ActionLibrary (List<Action> theActions)
动作库(列出动作)
当我从Guice请求ActionLibrary的实例时,我希望Guice识别两个注册的操作类(FooAction、BarAction),并将它们传递到构造函数中。这里的动机是,当我添加第三个操作时,它将与在模块中注册它一样简单,并且它将自动添加到构造函数中的列表中
这可能吗 你想要的是。具体地说,您希望绑定一个集合
(不是列表
,但是集合
可能是您真正想要的):
Multibinder<Action> actionBinder = Multibinder.newSetBinder(binder(), Action.class);
actionBinder.addBinding().to(FooAction.class);
actionBinder.addBinding().to(BarAction.class);
Multibinder actionBinder=Multibinder.newSetBinder(binder(),Action.class);
actionBinder.addBinding().to(FooAction.class);
actionBinder.addBinding().to(BarAction.class);
那么你可以<代码> @注销< /代码> <代码>设置<代码>任何地方。
< p>让我告诉你我认为是一个更好的多绑定的方式。如果希望Action
s是可插拔的,并且允许任何人添加它们,那么为用户提供一个简单的模块
通常是很有用的,它隐藏了需要实例化多活页夹
。下面是一个例子:
public abstract class ActionModule extends AbstractModule {
private Multibinder<Action> actionBinder;
@Override protected void configure() {
actionBinder = Multibinder.newSetBinder(binder(), Action.class);
configureActions();
}
/**
* Override this method to call {@link #bindAction}.
*/
protected abstract void configureActions();
protected final LinkedBindingBuilder<Action> bindAction() {
return actionBinder.addBinding();
}
}
这种使用
模块
隐藏多活页夹的模式在Guice代码中使用。这是一个小的工作在前面,但保持干净的东西。如果需要,您还可以为MapBinder
执行类似操作。请记住,您可以根据需要实例化任意多个ActionModule
s。如果您对这种方法还有任何疑问,请告诉我:-)。。。这对于编写用于配置东西的库非常方便。非常干净和简单的方法+1如果实际需要List
,那该怎么办?为什么甚至CollectionList
都没有意义,因为Multibinder
的整个思想是从多个模块收集绑定。。。而且没有一个可靠的用户定义的项目顺序。如果您确实需要一个带有特定顺序的项目的列表,那么只有自己创建该列表并直接绑定它才有意义。但是,Multibinder
的典型用例是绑定一个接口的多个实现,在这种情况下,顺序通常不重要,并且您不需要多个相同的东西。
public final class MyStandardActionModule extends ActionModule() {
@Override protected void configureActions() {
bindAction().to(FooAction.class);
bindAction().to(BarAction.class);
// If you need to instantiate an action through a Provider, do this.
bindAction().toProvider(BazActionProvider.class);
// You can also scope stuff:
bindAction().to(MySingletonAction.class).in(Singleton.class);
}
}