You can use @Qualifier
along with @Autowired
. In fact spring will ask you explicitly select the bean if ambiguous bean type are found, in which case you should provide the qualifier
For Example in following case it is necessary provide a qualifier
@Component
@Qualifier("staff")
public Staff implements Person {}
@Component
@Qualifier("employee")
public Manager implements Person {}
@Component
public Payroll {
private Person person;
@Autowired
public Payroll(@Qualifier("employee") Person person){
this.person = person;
}
}
EDIT:
In Lombok 1.18.4 it is finally possible to avoid the boilerplate on constructor injection when you have @Qualifier, so now it is possible to do the following:
@Component
@Qualifier("staff")
public Staff implements Person {}
@Component
@Qualifier("employee")
public Manager implements Person {}
@Component
@RequiredArgsConstructor
public Payroll {
@Qualifier("employee") private final Person person;
}
provided you are using the new lombok.config rule copyableAnnotations (by placing the following in lombok.config in the root of your project):
# Copy the Qualifier annotation from the instance variables to the constructor
# see https://github.com/rzwitserloot/lombok/issues/745
lombok.copyableAnnotations += org.springframework.beans.factory.annotation.Qualifier
This was recently introduced in latest lombok 1.18.4.
- The blog post where the issue is discussed in detail
- The original issue on github
- And a small github project to see it in action
NOTE
If you are using field or setter injection then you have to place the @Autowired and @Qualifier on top of the field or setter function like below(any one of them will work)
public Payroll {
@Autowired @Qualifier("employee") private final Person person;
}
or
public Payroll {
private final Person person;
@Autowired
@Qualifier("employee")
public void setPerson(Person person) {
this.person = person;
}
}
If you are using constructor injection then the annotations should be placed on constructor, else the code would not work. Use it like below -
public Payroll {
private Person person;
@Autowired
public Payroll(@Qualifier("employee") Person person){
this.person = person;
}
}