Dependency injection Guice:构建对象/机器人腿的相关树

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) { } } 我想绑定两个不

我有一个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
。我怎样才能正确地绑定这些 @提供方法,考虑一组提供程序,它允许您指定一组基于名称或PARAM的方法返回不同的实例(在您的情况下,可能是A的子类型)。我认为它将有机会接触私人建造商


最后一个想法是:为什么不将构造函数留给一个公共的构造函数,以便库的用户可以手动注入依赖项?如果仅用于内部使用,则记录cTor也就足够了。

而不是使用<代码> @提供方法,考虑一组提供者,它允许您指定一组基于名称或PARAM的方法返回不同的实例(在您的情况下,可能是A的子类型)。我认为它将有机会接触私人建造商


最后一个想法是:为什么不将构造函数留给一个公共的构造函数,以便库的用户可以手动注入依赖项?如果这只是供内部使用,记录ctor也就足够了。

我认为您正在寻找的解决方案是私有模块

  • 您需要两个PrivateModule实例,B1和B2各一个
  • 将B粘结到适当的混凝土类型上
  • expose(A.class).annotatedWith(B1.class)

  • -dg

    我认为您正在寻找的解决方案是专用模块

  • 您需要两个PrivateModule实例,B1和B2各一个
  • 将B粘结到适当的混凝土类型上
  • 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);
                }
            });
    }