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

查看:151
本文介绍了我不能使用注释来指示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的相应primary属性。

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当多个候选人
有资格自动装配
单值依赖时,
首选项。如果确实

候选者中存在一个'主'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
注释元数据,并且
< bean primary =true | false/> 改为尊重

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.

参见 ref docs

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

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