Like Spring autowire by name when more than one bean matches found?

Suppose I have interfaces such as:

interface Country {} class USA implements Country {} class UK implements Country () 

And this xml configuration snippet:

 <bean class="USA"/> <bean id="country" class="UK"/> <bean id="main" class="Main"/> 

How can I control which of the dependencies is auto-connected below? I would like the UK.

 class Main { private Country country; @Autowired public void setCountry(Country country) { this.country = country; } } 

I am using Spring 3.0.3.RELEASE.

+73
spring
Dec 15 2018-10-12T00:
source share
5 answers

This is described in section 3.9.3 of the Spring 3.0 manual:

For reciprocal matching, the bean name is considered the default classifier value.

In other words, the default behavior is as if you added @Qualifier("country") to the setter method.

+82
Dec 15 '10 at 10:30
source share

You can use @Qualifier annotation

From here

Fine-tune auto-tuning based on annotations with qualifiers

Since auto-negotiation by type can lead to multiple candidates, it is often necessary to have more control over the selection process. One way to achieve this is with the Spring @Qualifier annotation. This allows you to associate qualifier values ​​with specific arguments, narrowing the set of type matches so that a specific bean is selected for each argument. In the simplest case, this may be a simple descriptive value:

 class Main { private Country country; @Autowired @Qualifier("country") public void setCountry(Country country) { this.country = country; } } 

This will use the UK by adding an identifier in the USA bean and use this if you want the USA.

+47
Dec 15 '10 at 8:13
source share

Another way to achieve the same result is to use the @Value annotation:

 public class Main { private Country country; @Autowired public void setCountry(@Value("#{country}") Country country) { this.country = country; } } 

In this case, the string "#{country} is a Spring expression (SpEL) expression that evaluates to a bean named country .

+8
Aug 12 '14 at 21:24
source share

Another solution with resolution by name:

 @Resource(name="country") 

It uses the javax.annotation package, so it doesn't matter Spring, but Spring supports it.

+4
02 mar. '17 at 19:22
source share

In some cases, you can use the @Primary annotation.

 @Primary class USA implements Country {} 

Thus, it will be selected as autorun autorun by default, while there is no need to use an autowire candidate on another bean.

for mo deatils, look at Autowiring two beans that implement the same interface - how to set the default bean for auto-tuning?

+2
Sep 07 '16 at 12:53 on
source share



All Articles