Google 使用注释和键的 Guice 绑定 class

Google Guice binding using Annotation and Key class

假设我们有 A.java 接口,由 AImpl.javaB.javaBimpl.java

实施

以上类绑定在两个模块中如下

Module1 {
    bind(A.class).to(AImpl.class);
    bind(B.class).to(BImpl.class);
}

Module2 {
    Key<A> aKey = Key.get(A.class, AnAnnot.class);
    bind(aKey).to(AImpl.class);
    Key<B> bKey = Key.get(B.class, AnAnnot.class);
    bind(bKey).to(BImpl.class);
}


Class AImpl implements A {
}

Class BImpl implements B {

@Inject
BImpl(A aImpl) {
 //??
}
}

BImpl 引用 A

对于使用 Annotation 绑定的 BImpl,我想要相应的 aImpl,使用 Annotation 绑定,但这里我得到的 aImpl 没有使用 Annotation 绑定

请推荐

我可以使用以下模式实现。可能有更简单的方法。很高兴知道更多

A.java

public interface A {
    String aMethod();
}

AImpl.java

public class AImpl implements A {

    private String moduleName;

    public AImpl(String moduleName) {
        this.moduleName = moduleName;
    }

    @Override
    public String aMethod() {
        return moduleName;
    }
}

B.java

public interface B {
    String bMethod();
}

Bimpl.java

public class BImpl implements B {
    private final A a;

    BImpl(A a) {
        this.a = a;
    }

    @Override
    public String bMethod() {
        return a.aMethod();
    }
}

AnAnnot.java

@Target(PARAMETER)
@Retention(RUNTIME)
@BindingAnnotation
public @interface AnAnnot {
}

BProvider.java

public class BProvider  implements Provider<B> {
    private final A a;

    @Inject
    BProvider(A a) {
        this.a = a;
    }

    @Override
    public B get() {
        return new BImpl(a);
    }
}

BHavingAnnotatedA.java

public class BHavingAnnotatedA implements Provider<B> {
    private final A a;

    @Inject
    BHavingAnnotatedA(@AnAnnot A a) {
        this.a = a;
    }

    @Override
    public B get() {
        return new BImpl(a);
    }
}

ABModule1.java

public class ABModule1 extends AbstractModule {

    @Override
    protected void configure() {
        bind(A.class).to(AImpl.class);
        bind(B.class).toProvider(BProvider.class);
    }
}

ABModule2.java

public class ABModule2 extends AbstractModule {

    @Override
    protected void configure() {
        Key<A> aKey = Key.get(A.class, AnAnnot.class);
        bind(aKey).to(AImpl.class);
        Key<B> bKey = Key.get(B.class, AnAnnot.class);
        bind(bKey).toProvider(BHavingAnnotatedA.class);
    }
}