The guice AbstractModule install method

JavaGuice

Java Problem Overview


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?

Java Solutions


Solution 1 - Java

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][3].

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][2] or this SO answer for more on de-duplicating bindings.

[2]: https://web.archive.org/web/20161219130859/http://www.mattinsler.com/post/26548709502/google-guice-module-de-duplication "Guicey Tips - Google Guice Module De-Duplication" [3]: https://google.github.io/guice/api-docs/latest/javadoc/com/google/inject/assistedinject/FactoryModuleBuilder.html [4]: https://stackoverflow.com/q/20735211/1426891 "Ensure Module Is Loaded Only Once In Guice"

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMykelXIIIView Question on Stackoverflow
Solution 1 - JavaJeff BowmanView Answer on Stackoverflow