Question

What does the method install() from the AbstractModule class do? Can someone explain it to me? From the docs I read from the guice site all I could get was:

Uses the given module to configure more bindings.

Configure what bindings exactly? The bindings from the installed module or the bindings of the class that invoked the install method?

Was it helpful?

Solution

install allows for composition: Within its configure method, FooModule may install FooServiceModule (for instance). This would mean that an Injector created based only on FooModule will include bindings and providers in both FooModule and FooServiceModule.

You may see install used to split a Module into logical sub-modules for ease of readability or testing, or for a high-level Module to ensure its dependencies are configured. You might also use it to instantiate module instances with different constructor parameters (binding multiple data stores, for instance), or to install automatically-generated module instances like those created through FactoryModuleBuilder.

Module composition can be a double-edged sword, because duplicate bindings are not allowed: If your FooModule and BarModule both install the same dependent module, and the bindings are not exact duplicates (e.g. if a Module instantiates an object in its configure method), Guice will fail to create any Injector that installs both FooModule and BarModule due to the duplicate binding. You could work around this by defining equals and hashCode on your Modules, or by managing your composition such that any Module is either top-level or installed in exactly one other Module (but never both).

See this archived blog or this SO answer for more on de-duplicating bindings.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top