dependency-injectionannotationsguicerobot-legs-problem

Guice: Building Related Trees of Objects / Robot Legs


I have a class A that holds a class B like this:

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

I'd like to bind two different A's, one annotated @AhasB1 and another @AhasB2. How can I bind these correctly?


Solution

  • Here's how I did it using 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);
                }
            });
    }