The guice AbstractModule install method

喜你入骨 提交于 2019-12-18 12:47:34

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/21446685/the-guice-abstractmodule-install-method

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!