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

蹲街弑〆低调 提交于 2020-01-23 07:57:07

问题


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?


回答1:


@Qualifier("order-url")

and respectively name your component order-url

@Component("order-url")



回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/3512546/is-it-possible-to-use-multiple-qualifier-annotation-in-spring

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!