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

最后都变了- 提交于 2019-12-01 21:43:20

You can achieve this using 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, in which you'd want to (for instance) expose a @Left Leg and a @Right Leg where the Leg object is exactly the same but you've bound different Foot implementations (LeftFoot and RightFoot) further down in the hierarchy.

At this point, you're not specifying "who is getting it", but you're exposing a slightly different Injector graph for one consumer versus the other.

install(new PrivateModule() {
  bind(Authorizer.class).to(ImplA.class);
  expose(SomeClass.class);
});
install(new PrivateModule() {
  bind(Authorizer.class).to(ImplB.class);
  expose(SomeOtherClass.class);
});
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!