Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to use multiple @Qualifier annotation in Spring?

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?

like image 670
Fixpoint Avatar asked Aug 18 '10 13:08

Fixpoint


1 Answers

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.

like image 148
nicholas.hauschild Avatar answered Sep 21 '22 14:09

nicholas.hauschild