Kevin
Kevin

Reputation: 6292

Guice binding two different class to same interface with annotation

I have got a question about binding in Guice.

I have got two classes (MyClass1 and MyClass2) both implement the same interface, say: IMyInteface.

I have got the binding configured as:

bind(IMyInterface.class).annotatedWith(Class1.class).to(MyClass1.class); bind(IMyInterface.class).annotatedWith(Class2.class).to(MyClass2.class);

The Class1 and Class2 are annotations defined.

Now, if I use this code in the client:

    Injector injector = Guice.createInjector(new MyModule());
    IMyInterface c = injector..getInstance(IMyInterface.class);

The Guice won't know which implementation I want to have for IMyInterface. Is there anyway I can specify the annotation at this stage to selectively say: I want the implementation of MyClass2?

Many thanks

Upvotes: 1

Views: 2338

Answers (1)

rodion
rodion

Reputation: 15029

I think you can do:

injector.getInstance(Key.get(IMyInterface.class, Class2.class));

Edit: There appears to be a similar question with a similar answer here.

Upvotes: 2

Related Questions