Dependency injection Guice:构建对象/机器人腿的相关树
我有一个a类,B类是这样的:Dependency injection Guice:构建对象/机器人腿的相关树,dependency-injection,annotations,guice,robot-legs-problem,Dependency Injection,Annotations,Guice,Robot Legs Problem,我有一个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) { } } 我想绑定两个不
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
。我怎样才能正确地绑定这些请不要使用<代码> @提供方法,考虑一组最后一个想法是:为什么不将构造函数留给一个公共的构造函数,以便库的用户可以手动注入依赖项?如果仅用于内部使用,则记录cTor也就足够了。而不是使用<代码> @提供方法,考虑一组
最后一个想法是:为什么不将构造函数留给一个公共的构造函数,以便库的用户可以手动注入依赖项?如果这只是供内部使用,记录ctor也就足够了。我认为您正在寻找的解决方案是私有模块
expose(A.class).annotatedWith(B1.class)
-dg我认为您正在寻找的解决方案是专用模块
expose(A.class).annotatedWith(B1.class)
-dg以下是我如何使用
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);
}
});
}
下面是我如何使用
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);
}
});
}