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;
    }
  • 相关阅读:
    为什么我要学习qt quick
    geometory Intersect
    删除kubernetes节点的正确姿势
    乞丐版docker私有仓库搭建
    kubernetes集群中由于某些原因导致etcd节点没有删干净,需要手动清理etcd节点
    k8s coredns设置上游name server
    虚拟机架设koolshare软路由
    文件类型特征码
    深入字节码 -- 计算方法执行时间
    启迪思维:二叉树
  • 原文地址:https://www.cnblogs.com/shamgod/p/5235783.html
Copyright © 2011-2022 走看看