用Guice注入班级集合 [英] Injecting Collection of Classes with Guice
问题描述
我正在尝试使用Google Guice 2.0注入内容,并且具有以下结构:
I'm trying to inject things with Google Guice 2.0 and I have the following structure:
FooAction implements Action
BarAction implements Action
然后我有了一个带有以下构造函数的ActionLibrary:
I then have an ActionLibrary with the following constructor:
ActionLibrary (List<Action> theActions)
当我从Guice请求一个ActionLibrary实例时,我希望Guice识别两个已注册的Action类(FooAction,BarAction)并将它们传递给构造函数.这样做的动机是,当我添加第三个动作BazAction时,就像在Module中注册它一样简单,它会自动添加到构造函数中的列表中.
When I request an instance of ActionLibrary from Guice, I would like Guice to identify both of the registered Action classes (FooAction, BarAction) and pass them into the constructor. The motivation here being that when I add a third action BazAction, it would be as simple as registering it in the Module and it would automatically be added to the list in the constructor.
这可能吗?
推荐答案
您想要的是多绑定.具体来说,您想绑定Set<Action>
(而不是List
,但是无论如何Set
可能都是您真正想要的)绑定,如下所示:
What you want for this is Multibindings. Specifically, you want to bind a Set<Action>
(not a List
, but a Set
is probably what you really want anyway) like this:
Multibinder<Action> actionBinder = Multibinder.newSetBinder(binder(), Action.class);
actionBinder.addBinding().to(FooAction.class);
actionBinder.addBinding().to(BarAction.class);
然后您可以在任何地方@Inject
Set<Action>
.
Then you can @Inject
the Set<Action>
anywhere.
这篇关于用Guice注入班级集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!