I am using Microprofile and I have a question. I have an interface with a method inside:
public interface CheckData extends Serializable{
MyObject retrieveData(String name);
}
This interface is implemented by 2 different classes( Class A and Class B).
In the service class I need to use class A or class B based on a condition.
I did the @Inject of my interface:
@ApplicationScoped
public class MyService{
@Inject
private CheckData checkData;
public Response manageData{
...
if(condition)
checkData.retrieveData(name) // i needed Class A implementation
if(condition)
checkData.retrieveData(name) // i needed Class B implementation
}
}
how do you specify which implementation to use?
I solved it this way. I have created a class with two qualifiers:
public class MyQualifier {
@Qualifier
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.TYPE, ElementType.METHOD})
public @interface ClassifierOne {
}
@Qualifier
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.TYPE,ElementType. METHOD})
public @interface ClassifierTwo {
}
}
later I added the qualifiers to the classes that implement the interface:
@ClassifierOne
public class A implements CheckData{
...
}
@ClassifierTwo
public class B implements CheckData{
...
}
Finally I injected the interface specifying the qualifier:
@Inject
@ClassifierOne
private CheckData myClassA;
@Inject
@ClassifierTwo
private CheckData myClassB;
I hope it is correct and can help others.
Thanks to @Turo and @Asif Bhuyan for the support