春天@Autowired和@Qualifier [英] Spring @Autowired and @Qualifier
问题描述
通过@Autowired自动检测到吗?使用@Qualifier时是否按名称进行依赖项注入?我们如何使用这些批注进行setter和构造函数注入?
Is it auto detected with @Autowired? Is it dependency injection by name when @Qualifier is used? How can we do setter and constructor injection using these annotations?
推荐答案
您可以将@Qualifier
与@Autowired
一起使用.实际上,如果发现模棱两可的bean类型,spring会询问您是否明确选择了bean,在这种情况下,您应该提供限定符
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;
}
}
在Lombok 1.18.4中,当您具有@Qualifier时,最终有可能避免构造函数注入的样板,因此现在可以执行以下操作:
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;
}
前提是您使用的是新的lombok.config规则copyableAnnotations(将以下内容放在lombok.config中的项目根目录中):
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
最近在最新的lombok 1.18.4中引入了此功能.
This was recently introduced in latest lombok 1.18.4.
- 原始问题
- 和一个小的github 项目,以了解其运行情况
- 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
如果使用的是场注入或二传手注入,则必须将@Autowired和@Qualifier放在如下所示的场或二传手函数的顶部(其中任何一个都可以工作)
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;
}
或
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;
}
}
这篇关于春天@Autowired和@Qualifier的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!