简体   繁体   English

是否可以在Spring中使用多个@Qualifier注释?

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

I have a set of beans that are characterized by two properties. 我有一组以两个属性为特征的bean。 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. 例如,有可能是一个Order本地日志序列化, Order串行日志记录Web服务调用, Customer串行跟踪URL和Customer串行跟踪URL。

This is why I'd like to use two @Qualifier annotations like this: 这就是为什么我想使用这样的两个@Qualifier注释:

@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. 我知道这个问题相当陈旧,但这是自Spring 2.5以来你应该能够完成的事情。

You can create your own annotations that are themselves annotated with @Qualifier , a form of annotation composition. 您可以创建自己的注释,这些注释本身使用@Qualifier注释,这是一种注释组合形式。 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. 以下是解释此过程的Spring 2.5参考文档的链接。 Please note that it is for Spring 2.5 and may be out of date with regards to more recent versions of Spring. 请注意,它适用于Spring 2.5,可能会因更新版本的Spring而过时。

@Qualifier("order-url")

并分别命名您的组件order-url

@Component("order-url")

Of course I don't know all the details, but this issue is more like a task for Decorator pattern . 当然我不知道所有细节,但这个问题更像是Decorator模式的任务。 Probably, you may bound this in a Spring config if it's necessary. 也许,如果有必要,你可以在Spring配置中绑定它。

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. 或者,我同意Bozho的观点,你可以在Spring bean中使用一些名称约定,以便bean名称可以反映其责任和应用领域。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM