我不能使用注释来指示 bean 是主 bean [英] Can't I use annotation to indicate a bean is a primary bean

查看:21
本文介绍了我不能使用注释来指示 bean 是主 bean的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们知道在 Spring 中,<bean>有一个属性primary",表示如果有多个 bean 可用于自动装配到一个属性,则该 bean 是第一个候选对象.

We know in Spring, <bean> has an attribute "primary" to indicate a bean is the first candidate if there are multiple beans are available to be autowired to a property.

但是现在我所有的 bean 定义都是使用 @Component/@Service 等声明的,我找不到可以用来声明 bean 的相应主要"属性.

But now all my bean definition are declared using @Component/@Service, etc, I can't find the corresponding "primary" attribute I can use to declare a bean.

请告诉我如何实现这一点,谢谢.

Please advise how can I achieve this, thanks.

推荐答案

在 Spring 3.0 中,您使用 @Primary.

In Spring 3.0, you use @Primary.

表示应该给一个bean多个候选人时的偏好有资格自动装配一个单值依赖.如果正好一个主"豆存在于候选人,它将是自动装配的价值.

Indicates that a bean should be given preference when multiple candidates are qualified to autowire a single-valued dependency. If exactly one 'primary' bean exists among the candidates, it will be the autowired value.

可直接用于任何类或用 Component 间接注释或使用 Bean 注释的方法.

May be used on any class directly or indirectly annotated with Component or on methods annotated with Bean.

在班级级别使用 Primary除非组件扫描是无效的正在使用.如果主注释类通过 XML 声明,Primary注释元数据被忽略,并且 是反而受到尊重.

Using Primary at the class level has no effect unless component-scanning is being used. If a Primary-annotated class is declared via XML, Primary annotation metadata is ignored, and <bean primary="true|false"/> is respected instead.

参见 参考文档.

这篇关于我不能使用注释来指示 bean 是主 bean的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆