![](/img/trans.png)
[英]Guice - How to share the same Singleton instance through multiple injectors/modules
[英]Guice - How to let multiple multiple modules contribute to one thing?
我想知道是否可以让模块进行特定绑定,然后再注入这些绑定的组合。
简单示例:我有一个应该注入的List<SomeType>
并且多个模块应该能够向该列表添加/绑定元素。 基本上使用跨不同模块的绑定(或多重绑定,就此而言)。 我怎样才能做到这一点,哪种方法最好? 想不出什么。
但是......你必须使用Set
而不是List
。
此外,在开始之前,请注意,虽然 Multibinder 是一个扩展,但它已经集成到了几个版本的主要 Guice 工件中。
创建一个通用的静态方法,如下所示:
public static LinkedBindingBuilder<SomeType> bindSomeTypeSetElement(Binder binder) {
return Multibinder.newSetBinder(binder, SomeType.class).addBinding();
}
我告诉你写这样一个方法是因为之后会更容易找到绑定定义,如果你想将SomeType
更改为OtherType
,在一种方法中会更容易完成。 最后,如果您想更改绑定(例如,使用注释进行标识),也更容易。
现在在要绑定它的模块中,只需在configure
方法中编写以下代码:
import static path.to.SomeTypeBinder.bindSomeTypeSetElement;
public void configure() {
bindSomeTypeSetElement(binder()).toInstance(new ConcreteType());
bindSomeTypeSetElement(binder()).to(SecondConcreteType.class);
bindSomeTypeSetElement(binder()).toProvider(new ThirdConcreteTypeProvider());
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.