Question

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.

Was it helpful?

Solution

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.

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top