栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Spring @Autowired和@Qualifier

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Spring @Autowired和@Qualifier

你可以

@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;    }}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/420513.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号