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
You would install your other modules
protected void configure(){
install(new ProdDbModule());
install(new ProdPubSubModule());
// etc.
}
Comments
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.
Comments
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
Modulerather 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 Comments
Guice.createInjector(new ProdDbModule(), new ProdPubSubModule(), new ProdModule())?