使用具有相似依赖关系的两个不同模块创建 guice 注入器

Creating a guice injector with two different modules having similar dependencies

假设我有两个模块ModuleAModuleB,它们是自给自足的,可以作为独立模块使用。这两个模块都依赖于第三个模块 ModuleC,例如

install(new ModuleC());

现在,我有一个用例,我需要用两个模块 A 和 B 创建一个注入器。我这样做了:

Guice.createInjector(new ModuleA(), new ModuleB());

它按预期抛出一个 CreationException,表示已经在其中一个模块中配置了对某个 class 的绑定。请记住,我无权更改 ModuleAModuleB,我该如何让它发挥作用?

我尝试使用 Modules.combine(Modules... modules) 但这并没有解决我的问题。有解决办法吗?

假设您定义了以下绑定:

模块 C:

  • C1

模块A

  • A1
  • A2

模块B

  • B1
  • B2

现在,当您执行 Guice.createInjector(new ModuleA(),new ModuleB())Modules.combine(..) 时, 您的最终绑定列表将是:

  • A1
  • A2
  • B1
  • B2
  • C1(继承自 A)
  • C1 (!)(继承自 B)

由于 C1 绑定列出了两次,这会产生冲突并导致 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())

您的最终绑定列表如下:

  • A1
  • A2
  • B1
  • B2
  • C1(继承自 A)
  • C1(继承自 B)

ModuleA 继承的 C1 绑定将被删除,取而代之的是 ModuleB 中定义的 C1 绑定,从而解决冲突。