Guice:根据谁得到它注入不同的实现?

Guice: inject different implementation depending on who is getting it?

我有两个第三方 类,它们都实现了 Authorizer 接口。我需要为每个注入不同的实现。

如果我执行 @Provides,我如何实施才能提供 运行 时所需的实施?提供者不知道谁要求注射。

理论上我可以使用@Named,但我无法修改注入的代码。我想做类似的事情:

bind(Authorizer.class).to(ImplA.class).for(SomeClass.class)
bind(Authorizer.class).to(ImplB.class).for(SomeOtherClass.class)

显然,"for" 代码不存在,但是是否有一些等效的方法可以做到这一点?

您可以使用 Private Modules, which let you install (mutually-inaccessible) conflicting bindings to be used in constructing a limited set of non-conflicting exposed bindings. This is often seen as a solution to the robot legs problem 实现此目的,其中您希望(例如)公开一个 @Left Leg 和一个 @Right Leg,其中 Leg 对象是完全相同,但您在层次结构中进一步绑定了不同的 Foot 实现(LeftFootRightFoot)。

此时,您没有指定 "who is getting it",但您为一个消费者和另一个消费者公开了一个略有不同的注入器图。

install(new PrivateModule() {
  bind(Authorizer.class).to(ImplA.class);
  expose(SomeClass.class);
});
install(new PrivateModule() {
  bind(Authorizer.class).to(ImplB.class);
  expose(SomeOtherClass.class);
});