简体   繁体   中英

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. 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

But... you'll have to use a Set and not a 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.

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. 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:

import static path.to.SomeTypeBinder.bindSomeTypeSetElement;

public void configure() {
  bindSomeTypeSetElement(binder()).toInstance(new ConcreteType());
  bindSomeTypeSetElement(binder()).to(SecondConcreteType.class);
  bindSomeTypeSetElement(binder()).toProvider(new ThirdConcreteTypeProvider());
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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