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()?
Asked
Active
Viewed 2.2k times
3 Answers
32
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.

ColinD
- 108,630
- 30
- 201
- 202
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);

Alexander Oh
- 24,223
- 14
- 73
- 76
-
And what would be the difference w.r.t. simply calling `Guice.createInjector(new ProdDbModule(), new ProdPubSubModule(), new ProdModule())`? – Óscar López Jun 21 '19 at 15:52
-
4nothing. 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. – Alexander Oh Jun 21 '19 at 17:21