guice AbstractModule安装方法 [英] The guice AbstractModule install method

查看:148
本文介绍了guice AbstractModule安装方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

推荐答案

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

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.

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

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.

模块组合可以是一把双刃剑,因为不允许重复绑定:如果你的FooModule和BarModule都是安装相同的依赖模块,并且绑定不是完全重复(例如,如果某个模块在其 configure 方法),由于重复绑定,Guice将无法创建任何安装FooModule和BarModule的Injector。您可以通过在模块上定义等于 hashCode 来解决此问题,或者通过管理您的组合使得任何模块都是无论是顶级还是安装在另一个模块中(但从不同时安装)。

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).

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

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

这篇关于guice AbstractModule安装方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆