I have a set of beans that are characterized by two properties. They are basically serializers for different classes and for different purposes.
For example, there may be an Order
serializer for local log, Order
serializer for logging webservice call, Customer
serializer for tracking URL and Customer
serializer for tracking URL.
This is why I'd like to use two @Qualifier
annotations like this:
@Autowired
@Qualifier("order")
@Qualifier("url")
private Serializer<Order> orderSerializer;
Unfortunately, compiler complains about duplicate annotations in this case. Are there any workarounds or alternative solutions to this problem?
I understand that this question is rather old, but this is something you should be able to accomplish since Spring 2.5.
You can create your own annotations that are themselves annotated with @Qualifier
, a form of annotation composition. Spring will honor these qualifiers as though they are their own.
Consider these two annotation types, named similarly to your example:
@Target({ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.TYPE, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Qualifier
public @interface MyOrderQualifier {
}
@Target({ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER, ElementType.TYPE, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Qualifier
public @interface MyUrlQualifier {
}
You should be able to use both of these annotations on your field, since they are independent annotations.
@Autowired
@MyOrderQualifier
@MyUrlQualifier
private Serializer<Order> orderSerializer;
Here is a link to the Spring 2.5 reference documentation explaining this process. Please note that it is for Spring 2.5 and may be out of date with regards to more recent versions of Spring.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With