Fixpoint
Fixpoint

Reputation: 9870

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?

Upvotes: 10

Views: 20521

Answers (3)

nicholas.hauschild
nicholas.hauschild

Reputation: 42834

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.

Upvotes: 15

wax
wax

Reputation: 2431

Of course I don't know all the details, but this issue is more like a task for Decorator pattern. Probably, you may bound this in a Spring config if it's necessary.

Or, I agree with Bozho here, you could use some name conventions across you Spring beans, so that bean name could reflect its responsibility and area of application.

Upvotes: 0

Bozho
Bozho

Reputation: 597342

@Qualifier("order-url")

and respectively name your component order-url

@Component("order-url")

Upvotes: 5

Related Questions