假设我有两个模块 ModuleA
和 ModuleB
,它们是自给自足的,可以用作独立模块。这两个模块都依赖于第三个模块 ModuleC
,例如
install(new ModuleC());
现在,我有一个用例,我需要创建一个包含两个模块 A 和 B 的注入(inject)器。我这样做了:
Guice.createInjector(new ModuleA(), new ModuleB());
它按预期抛出一个 CreationException
,表示已经在其中一个模块中配置了对某个类的绑定(bind)。请记住,我无权更改 ModuleA
和 ModuleB
,我该如何让它工作?
我尝试使用 Modules.combine(Modules... modules)
但这并没有解决我的问题。有什么解决方案吗?
最佳答案
假设您定义了以下绑定(bind):
模块C:
- C1
模块A
- A1
- A2
模块B
- B1
- B2
现在,当您执行 Guice.createInjector(new ModuleA(),new ModuleB())
或 Modules.combine(..)
时,
您的最终绑定(bind)列表将是:
- A1
- A2
- B1
- B2
- C1(继承自 A)
- C1 (!)(继承自 B)
由于 C1 绑定(bind)被列出两次,这会产生冲突并导致 CreationException
。
但是如果你使用 Modules.override()相反:
Returns a builder that creates a module that overlays override modules over the given modules. If a key is bound in both sets of modules, only the binding from the override modules is kept.
例如通过做
Modules.override(new ModuleA()).with(new ModuleB())
您的最终绑定(bind)列表如下:
- A1
- A2
- B1
- B2
C1(继承自 A)- C1(继承自 B)
从 ModuleA 继承的 C1 绑定(bind)将被丢弃,取而代之的是 ModuleB 中定义的 C1 绑定(bind),从而解决冲突。
关于java - 使用具有相似依赖关系的两个不同模块创建 guice 注入(inject)器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40975354/