java 我不能使用注解来表明一个 bean 是一个主 bean
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1998447/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Can't I use annotation to indicate a bean is a primary bean
提问by Matt
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.
我们知道在 Spring 中,<bean> 有一个属性“primary”,表示如果有多个 bean 可用于自动装配到一个属性,则该 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.
但是现在我所有的 bean 定义都是使用 @Component/@Service 等声明的,我找不到可以用来声明 bean 的相应“主要”属性。
Please advise how can I achieve this, thanks.
请指教我怎样才能做到这一点,谢谢。
回答by skaffman
In Spring 3.0, you use @Primary.
在 Spring 3.0 中,您使用@Primary.
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.
May be used on any class directly or indirectly annotated with Component or on methods annotated with Bean.
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,它将是自动装配的值。
可用于任何直接或间接用 Component 注释的类或用 Bean 注释的方法。
除非正在使用组件扫描,否则在类级别使用 Primary 无效。如果通过 XML 声明主注释类,主注释元数据将被忽略,
<bean primary="true|false"/>而是被尊重。
See ref docs.
请参阅参考文档。
回答by Andre Rodrigues
The @Primary annotation will only work if you are using Spring 3.0.
@Primary 注释仅在您使用 Spring 3.0 时才有效。
In Spring 2.5 there's no equivalent annotation for the primary attribute. You have to use the @Qualifier annotation to specify which bean you want to inject. Another option is to define your own qualifier annotation for the same purpose.
在 Spring 2.5 中,主属性没有等效的注释。您必须使用 @Qualifier 批注来指定要注入的 bean。另一种选择是为相同的目的定义您自己的限定符注释。
See the docsfor more information.
有关更多信息,请参阅文档。

