Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Guice - How to let multiple multiple modules contribute to one thing?

Tags:

java

guice

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.

like image 900
Johnny Avatar asked Dec 08 '25 10:12

Johnny


1 Answers

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());
}
like image 156
Olivier Grégoire Avatar answered Dec 10 '25 00:12

Olivier Grégoire



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!