Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't I use annotation to indicate a bean is a primary 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.

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.

like image 646
Matt Avatar asked Jan 04 '10 09:01

Matt


People also ask

What is @bean annotation used for?

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.

What is difference between @bean and @component annotation?

@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.

What is difference between @qualifier and primary?

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.

What does @primary annotation do?

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.


2 Answers

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.

like image 185
skaffman Avatar answered Oct 24 '22 06:10

skaffman


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.

like image 34
Andre Rodrigues Avatar answered Oct 24 '22 06:10

Andre Rodrigues