I cannot use annotation to indicate that a bean is the main bean

We know in Spring that <bean> has a "primary" attribute, indicating that a bean is the first candidate if there are several beans available to auto-connect to the property.

But now all my bean definitions are declared using @ Component / @ Service, etc., I canโ€™t find the corresponding โ€œprimaryโ€ attribute that I can use to declare a bean.

Please advise how I can achieve this, thanks.

+6
java spring annotations autowired
source share
2 answers

In Spring 3.0, you are using @Primary .

Indicates that a bean should be given preference when several candidates qualify for an unambiguous dependency. If exactly one "primary" bean exists among the candidates, this will automatically be the value.

It can be used for any class directly or indirectly annotated by the Component or on methods annotated using Bean.

Using Primary at the class level has no effect if component scanning is used. If the main annotated class is declared via XML, Primary annotation metadata is ignored, and <bean primary="true|false"/> respected instead.

See ref docs .

+22
source share

@Primary annotations will only work if you are using Spring 3.0.

Spring 2.5 does not have equivalent annotation for the main attribute. You should use the @Qualifier annotation to indicate which bean you want to enter. Another option is to define your own classifier annotation for the same purpose.

See docs for more details.

+4
source share

All Articles