3

I am using RoboGuice 4.0beta2 , and i have this problem

I have several different objects that implement the same interface

call them A implements ITest B implements ITest C implements ITest

I have class D, that uses all 3 implementations together, each has a different purpose, but the same API for that

Inside class D i would like to inject A,B, and C, which have nothing to do with eachother,except the fact that they all implement the same interface

How would i configure the Module class to know that i mean different implementatios of ITest ?

Lena Bru
  • 13,521
  • 11
  • 61
  • 126

1 Answers1

3

Assuming you have the following configuration:

class D{
    @Inject ITest a;
    @Inject ITest b;
    @Inject ITest c;
}

you can set up your module like the following so you can inject the different types by @Name:

public class ABCModule extends AbstractModule {

    @Override
    protected void configure() {
        bind(ITest.class).annotatedWith(Names.named("a")).to(A.class);
        bind(ITest.class).annotatedWith(Names.named("b")).to(B.class);
        bind(ITest.class).annotatedWith(Names.named("c")).to(C.class);
    }
}

which allows you to inject the different types like so:

class D{
    @Inject @Named("a") ITest a;
    @Inject @Named("b") ITest b;
    @Inject @Named("c") ITest c;
}
John Ericksen
  • 10,995
  • 4
  • 45
  • 75