views:

197

answers:

2

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.

+4  A: 

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.

skaffman
Thanks I have upgraded to Spring 3.0, it works fine now.
Matt
+3  A: 

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.

Andre Rodrigues