简体   繁体   中英

Inject multiple interface implementations into class constructor

I'm new with Java Guice, and I have trouble with designing my application.
I'll try to explain my design and the desired result as simple as I can.

I have an interface called Ialgorithm , and 3 implementations of that interface, lets say IalgorithmA , IalgorithmB , IalgirthmC .

I have a class called myClass with the following constructor:

public myClass(Ialgorithm alg) {...}

Now I want to be able to inject an instance of one of the implementations of the Ialgorithm interface, using annotations: I want at the end to be able to write in my main:

// ... intialize an Injector with a Moudle that extents AbstractModule
myClass a = injecotr.getInstance(key.get(myClass.class,Aannotation.class));
myClass b = injecotr.getInstance(key.get(myClass.class,Bannotation.class));
myClass c = injecotr.getInstance(key.get(myClass.class,Cannotation.class));

I read a few tutorials in the web, but I couldn't find exact way to achieve this.

In addition, and after the above issue will be solved, I extend my question: Actually, The third implementation, IalgirthmC , is different from the two other implementations which contain a default constructor: its constructor is:

public IalgorithmC(Ialgorithm,int n) {...}

Now it becomes more complicated... because I want the Guice to inject the Ialgorithm parameter, but the int parameter shouldn't injected by the Guice (@Assisted), and this whole instance of IalgorithmC should be injected into myClass when using the Cannotaion .
Of course that I should provide a value for the int parameter and an annotation to the internal Ialgorithm in IalgorithmC .

Thank you all for any help.

这个问题讨论的是针对guice中多种实现的一种解决方案。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM