The guice AbstractModule install method

后端 未结 1 1607
遥遥无期
遥遥无期 2020-12-28 12:24

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

相关标签:
1条回答
  • 2020-12-28 12:42

    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.

    0 讨论(0)
提交回复
热议问题