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.
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.
One of the most important annotations in spring is the @Bean annotation which is applied on a method to specify that it returns a bean to be managed by Spring context. Spring Bean annotation is usually declared in Configuration classes methods. This annotation is also a part of the spring core framework.
@Component is a class-level annotation, but @Bean is at the method level, so @Component is only an option when a class's source code is editable. @Bean can always be used, but it's more verbose.
It's worth noting that if both the @Qualifier and @Primary annotations are present, then the @Qualifier annotation will have precedence. Basically, @Primary defines a default, while @Qualifier is very specific.
In this quick tutorial, we'll discuss Spring's @Primary annotation which was introduced with version 3.0 of the framework. Simply put, we use @Primary to give higher preference to a bean when there are multiple beans of the same type.
In Spring 3.0, you use @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.
See ref docs.
The @Primary annotation will only work if you are using 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.
See the docs for more information.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With