1

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

Kevin
  • 5,972
  • 17
  • 63
  • 87

1 Answers1

2

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.

Community
  • 1
  • 1
rodion
  • 14,729
  • 3
  • 53
  • 55