zoukankan      html  css  js  c++  java
  • SPRING IN ACTION 第4版笔记-第三章ADVANCING WIRING-004-消除BEAN自动装配的歧义@QUALIFIER及自定义注解

    一、

    The @Qualifier annotation is the main way to work with qualifiers. It can be
    applied alongside @Autowired or @Inject at the point of injection to specify which
    bean you want to be injected. For example, let’s say you want to ensure that the
    IceCream bean is injected into setDessert() :

    @Autowired
    @Qualifier("iceCream")
    public void setDessert(Dessert dessert) {
        this.dessert = dessert;
    }

    id为“iceCream”的bean会被注入

    二、

    以id为筛选条件,则万一类名一更改,则此自动装配会失效(@componet默认是以类名首字母小写为bean的id),另一相对的较好的做好是在bean的定义端也写@Qualifier,但不是指明id,而是指明特性

    1 @Component
    2 @Qualifier("cold")
    3 public class IceCream implements Dessert { ... }

    1 @Bean
    2 @Qualifier("cold")
    3 public Dessert iceCream() {
    4     return new IceCream();
    5 }

    注入

    @Autowired
    @Qualifier("cold")
    public void setDessert(Dessert dessert) {
        this.dessert = dessert;
    }

    三、

    但上述的例子,有多个合适的bean都标明@Qualifier("cold")时,还是会产生歧义,此时要自定义注解来解决

    1.

    @Target({ElementType.CONSTRUCTOR, ElementType.FIELD,
    ElementType.METHOD, ElementType.TYPE})
    @Retention(RetentionPolicy.RUNTIME)
    @Qualifier
    public @interface Cold { }

    2.

    @Target({ElementType.CONSTRUCTOR, ElementType.FIELD,
    ElementType.METHOD, ElementType.TYPE})
    @Retention(RetentionPolicy.RUNTIME)
    @Qualifier
    public @interface Creamy { }

    Now you can revisit IceCream and annotate it with @Cold and @Creamy , like this:

    @Component
    @Cold
    @Creamy
    public class IceCream implements Dessert { ... }
    Similarly, the Popsicle class can be annotated with @Cold and @Fruity

    Similarly, the Popsicle class can be annotated with @Cold and @Fruity :

    @Component
    @Cold
    @Fruity
    public class Popsicle implements Dessert { ... }

    Finally, at the injection point, you can use any combination of qualifier annotations

    necessary to narrow the selection to the one bean that meets your specifications. To
    arrive at the IceCream bean, the setDessert() method can be annotated like this:

    @Autowired
    @Cold
    @Creamy
    public void setDessert(Dessert dessert) {
    this.dessert = dessert;
    }
  • 相关阅读:
    JSON的数据格式
    KMP 算法
    爬虫原理
    快速求小于N的所有素数
    对程序员最具影响的书籍
    实现下拉更新UITableView EGORefreshTableHeaderView
    温习C/C++笔记——浅谈琐碎知识点(1)
    C++内存对齐
    SQL Server 安装程序无法获取 ASPNET 帐户的系统帐户信息
    Asp.Net生命周期事件
  • 原文地址:https://www.cnblogs.com/shamgod/p/5235783.html
Copyright © 2011-2022 走看看