Guice:根据谁获得它来注入不同的实现? [英] Guice: inject different implementation depending on who is getting it?

查看:102
本文介绍了Guice:根据谁获得它来注入不同的实现?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have two third-party classes, both of which take an implementation of an Authorizer interface. I need to inject each with a different implementation.

如果我执行 @Provides ,我该如何实现它以便它提供运行时所需的实现?提供者不知道是谁要求注射。

If I do an @Provides, how can I implement it so that it provides the implementation required at run time? The provider has no idea who is asking for the injection.

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

In theory I could use @Named, but I can't modify the code being injected. I want to do something like:

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

显然,for代码不存在,但是有一些等效的方法吗?

Obviously, the "for" code doesn't exist, but is there some equivalent way to do this?

推荐答案

您可以使用专用模块,允许您安装(相互不可访问的)冲突绑定,以用于构建一组有限的非冲突公开的绑定。这通常被视为机器人腿问题,你想要(例如)暴露一个 @Left Leg 和一个 @Right Leg 其中 Leg 对象完全相同但你绑定了不同的 Foot 层次结构中的实现( LeftFoot RightFoot )。

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.

此时,您没有指定谁来获取它,但是您为一个消费者与另一个消费者公开了一个略有不同的Injector图。

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);
});

这篇关于Guice:根据谁获得它来注入不同的实现?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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