40

Let's say I have a Guice module ProdModule that I would like to depend on other GuiceModules, ProdDbModule and ProdPubSubModule. How would I implement ProdModule's configure()?

3 Answers 3

57

You would install your other modules

protected void configure(){
    install(new ProdDbModule());
    install(new ProdPubSubModule());
    // etc.
}
33

While it can be convenient to use install, you don't even need to install the other modules as long as you provide all the necessary modules when you create your Injector:

Injector injector = Guice.createInjector(new ProdDbModule(),
    new ProdPubSubModule(), new ProdModule());

This can give you more flexibility to change out just one of these modules in your entry point class without needing to modify ProdModule itself. You can also indicate in a module what bindings it requires other modules to provide using the requireBinding methods.

11

You can use Modules.combine to create a new module that contains all the other modules. (See this link)

The differences:

  • this is not subject to tight coupling modules like install()
  • this creates a Module rather than an injector, which means you can easily add different modules to the injector.

Code

import com.google.inject.util.Modules;
Module module = Modules.combine(new ProdDbModule(),
  new ProdPubSubModule(), new ProdModule());
Injector injector = Guice.createInjector(module);
2
  • And what would be the difference w.r.t. simply calling Guice.createInjector(new ProdDbModule(), new ProdPubSubModule(), new ProdModule())? Commented Jun 21, 2019 at 15:52
  • 4
    nothing. combine is useful if you want to share the same list of modules in multiple places, and perhaps want a tree of modules instead of a list. Commented Jun 21, 2019 at 17:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.