Reputation: 3558
I was wondering if there is a way to specify that a subclass should get the qualifier of the container class. For example:
@Blue
@Default
public class Container {
@Inject
MyClass c;
}
Now if I inject the Container class using the @Blue
qualifier, is there any way to tell that also the MyClass
instance should be injected using the same qualifier? If not, it requires me to create a producer for each such case, and a constructor in the class Container
...
Upvotes: 0
Views: 362
Reputation: 793
One way to achieve this is to create a producer for MyClass. The producer method must have the InjectionPoint as parameter because we need the information about the declaring class. This can be achieved by using InjectionPoint#getBean.
With this information we can now select the qualifiers we are interested in (I suggest to introduce a @Transferable annotation that should be used by the qualifier definition to be more generic).
At least the producer bean must obtain all possible instances of MyClass. This can be achieved by using Instance .
At least we must iterate over the instances and select the matching implementation of MyType.
The implementation could look like this:
@Transferable
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Transferable {
}
@Blue
@Qualifier
@Transferable
@Retention(RetentionPolicy.RUNTIME
@Target({ElementType.FIELD, ElementType.TYPE})
public @interface Blue {
}
MyClassProducer
public class MyClassProducer {
@Inject
private Instance<MyClass> myClasses;
@Produces
@Any
public MyClass getMyClassFromTransferedAnnotations(InjectionPoint ip) {
Set<Annotations> qualifiers = ip.getBean().getQualifiers();
for(Annotation an : annotations) {
if(an.getAnnotationType().isAnnotationPresent(Transferable.class)) {
return myClasses.select(an.getAnnotationType);
}
}
return null; // Todo : think about throwing an UnsatisfiedDependenciesException
}
}
Upvotes: 1