你可以
@Qualifier与一起使用
@Autowired。实际上,如果发现模棱两可的bean类型,spring会询问你是否明确选择了bean,在这种情况下,你应该提供限定符
例如在以下情况下,有必要提供一个限定词
@Component@Qualifier("staff") public Staff implements Person {}@Component@Qualifier("employee") public Manager implements Person {}@Componentpublic Payroll { private Person person; @Autowired public Payroll(@Qualifier("employee") Person person){ this.person = person; }}编辑:
在Lombok 1.18.4中,最终可以避免使用@Qualifier时构造函数注入的样板,因此现在可以执行以下操作:
@Component@Qualifier("staff") public Staff implements Person {}@Component@Qualifier("employee") public Manager implements Person {}@Component@RequiredArgsConstructorpublic Payroll { @Qualifier("employee") private final Person person;}前提是你使用的是新的lombok.config规则copyableAnnotations(将以下内容放在lombok.config中的项目根目录中):
# Copy the Qualifier annotation from the instance variables to the constructor# see https://github.com/rzwitserloot/lombok/issues/745lombok.copyableAnnotations += org.springframework.beans.factory.annotation.Qualifier
最近在最新的lombok 1.18.4中引入了此功能。
- 详细讨论该问题的博客文章
- github上的原始问题
- 还有一个小的github项目,可以看到它的实际效果
注意
如果你正在使用字段注入或设置器注入,则必须将@Autowired和@Qualifier放在字段或设置器函数的顶部,如下所示(它们中的任何一个都可以)
public Payroll { @Autowired @Qualifier("employee") private final Person person;}要么
public Payroll { private final Person person; @Autowired @Qualifier("employee") public void setPerson(Person person) { this.person = person; } }如果使用构造函数注入,则应将注释放置在构造函数上,否则代码将无法工作。如下使用它-
public Payroll { private Person person; @Autowired public Payroll(@Qualifier("employee") Person person){ this.person = person; }}


