How does Spring autowire by name when more than one matching bean is found?
Solution 1:
This is documented in section 3.9.3 of the Spring 3.0 manual:
For a fallback match, the bean name is considered a default qualifier value.
In other words, the default behaviour is as though you'd added @Qualifier("country")
to the setter method.
Solution 2:
You can use the @Qualifier annotation
From here
Fine-tuning annotation-based autowiring with qualifiers
Since autowiring by type may lead to multiple candidates, it is often necessary to have more control over the selection process. One way to accomplish this is with Spring's @Qualifier annotation. This allows for associating qualifier values with specific arguments, narrowing the set of type matches so that a specific bean is chosen for each argument. In the simplest case, this can be a plain descriptive value:
class Main {
private Country country;
@Autowired
@Qualifier("country")
public void setCountry(Country country) {
this.country = country;
}
}
This will use the UK add an id to USA bean and use that if you want the USA.