简体   繁体   English

Guice - 如何让多个模块为一件事做出贡献?

[英]Guice - How to let multiple multiple modules contribute to one thing?

I'd like to know if it's possible to let modules make a specific binding and later inject the combination of those bindings.我想知道是否可以让模块进行特定绑定,然后再注入这些绑定的组合。

Simple example: I have a List<SomeType> that ought to be injected and multiple modules should be able to add/bind elements to that list.简单示例:我有一个应该注入的List<SomeType>并且多个模块应该能够向该列表添加/绑定元素。 Basically using bindings (or multibindings, for that matter) across different modules.基本上使用跨不同模块的绑定(或多重绑定,就此而言)。 How could I accomplish that and which approach would be best?我怎样才能做到这一点,哪种方法最好? Can't think of anything.想不出什么。

Use the Multibinder extension使用 Multibinder 扩展

But... you'll have to use a Set and not a List .但是......你必须使用Set而不是List

Also, before starting, note that while Multibinder is an extension, it's been integrated in the main Guice artifact for a few releases already.此外,在开始之前,请注意,虽然 Multibinder 是一个扩展,但它已经集成到了几个版本的主要 Guice 工件中。

Create a common static method like this:创建一个通用的静态方法,如下所示:

public static LinkedBindingBuilder<SomeType> bindSomeTypeSetElement(Binder binder) {
  return Multibinder.newSetBinder(binder, SomeType.class).addBinding();
}

I'm telling you to write such a method because it'll be easier to find the binding definition afterwards, and if you want to change SomeType to OtherType , it'll be easier done in one method.我告诉你写这样一个方法是因为之后会更容易找到绑定定义,如果你想将SomeType更改为OtherType ,在一种方法中会更容易完成。 Finally, if you want to change the binding (to use an annotation for identification, for instance), it's also easier.最后,如果您想更改绑定(例如,使用注释进行标识),也更容易。

Now in the modules you want to bind this, just write the following code in your configure methods:现在在要绑定它的模块中,只需在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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM