【问题标题】:Guice: Building Related Trees of Objects / Robot LegsGuice:构建对象/机器人腿的相关树
【发布时间】:2011-07-15 14:26:31
【问题描述】:
我有一个 A 类,它拥有一个像这样的 B 类:
class A {
private final B b;
@Inject
A(B b) {
this.b = b;
}
}
interface B {}
class B1 implements B {}
class B2 implements B {}
class Client() {
@Inject
Client(@AhasB1 A aHasB1, @AhasB2 A aHasB2) { }
}
我想绑定两个不同的 A,一个注释为 @AhasB1,另一个注释为 @AhasB2。我怎样才能正确绑定这些?
【问题讨论】:
标签:
dependency-injection
annotations
guice
robot-legs-problem
【解决方案1】:
这是我使用 PrivateModule 的方法。
public class MainModule extends AbstractModule {
@Override
protected void configure() {
install(new PrivateModule(){
@Override
protected void configure() {
bind(A.class).annotatedWith(AhasB1.class).to(A.class);
expose(A.class).annotatedWith(AhasB1.class);
bind(B.class).to(B1.class);
}
});
install(new PrivateModule(){
@Override
protected void configure() {
bind(A.class).annotatedWith(AhasB2.class).to(A.class);
expose(A.class).annotatedWith(AhasB2.class);
bind(B.class).to(B2.class);
}
});
}
【解决方案2】:
不使用@Provides 方法,而是考虑一组Provider<A> 类型,可能嵌套在类型A 中,授予您对私有ctor 的访问权限。或者将其设为受包保护的 ctor,并将提供程序放在与其相同的包中。或者,当然,您可以将您的 Module 类型移动到与 A 相同的包中。
另一个选项是AssistedInject,它允许您指定一组方法,这些方法将根据名称或参数返回不同的实例(在您的情况下,可能是 A 的子类型)。我认为它可以访问私有构造函数。
最后一个想法是:为什么不让 A 的构造函数公开,以便库的用户可以手动注入依赖项?如果这仅供内部使用,记录 ctor 也足够了。