Java guice AbstractModule 安装方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21446685/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 08:46:19  来源:igfitidea点击:

The guice AbstractModule install method

javaguice

提问by MykelXIII

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

什么方法install()AbstractModule类呢?有人可以向我解释一下吗?从我从 guice 网站阅读的文档中,我能得到的是:

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?

究竟配置什么绑定?来自已安装模块的绑定还是调用 install 方法的类的绑定?

采纳答案by Jeff Bowman

installallows for composition: Within its configuremethod, 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.

install允许组合:在其configure方法中,FooModule 可以安装 FooServiceModule(例如)。这意味着仅基于 FooModule 创建的注入器将在 FooModule 和 FooServiceModule 中包含绑定和提供程序。

You may see installused 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.

您可能会看到install用于将模块拆分为逻辑子模块以方便阅读或测试,或者用于高级模块以确保配置其依赖项。您还可以使用它来实例化具有不同构造函数参数的模块实例(例如,绑定多个数据存储),或者安装自动生成的模块实例,例如通过FactoryModuleBuilder创建的那些。

Module composition can be a double-edged sword, because duplicate bindings are not allowed: If your FooModule and BarModule both installthe same dependent module, and the bindings are not exact duplicates(e.g. if a Module instantiates an object in its configuremethod), 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 equalsand hashCodeon 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).

模块组合可能是一把双刃剑,因为不允许重复绑定:如果你的 FooModule 和 BarModule 都是install同一个依赖模块,并且绑定不是完全重复的(例如,如果一个模块在它的configure方法中实例化了一个对象),Guice 将由于重复绑定,无法创建安装 FooModule 和 BarModule 的任何注入器。你可以通过定义equalshashCode在你的模块上解决这个问题,或者通过管理你的组合来解决这个问题,这样任何模块要么是顶级的,要么正好安装在另一个模块中(但不能同时安装)。

See this archived blogor this SO answerfor more on de-duplicating bindings.

有关重复数据删除绑定的更多信息,请参阅此存档博客此 SO 答案