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;
    }
  • 相关阅读:
    关于vue2.x使用axios以及http-proxy-middleware代理处理跨域的问题
    vue-resource的使用
    从头开始开发一个vue幻灯片组件
    图与例解读Async/Await
    浅谈web缓存
    APICloud框架——总结一下最近开发APP遇到的一些问题 (三)
    编写现代 CSS 代码的 20 个建议
    仿微信联系人列表滑动字母索引
    初来乍到,向各位大牛虚心学习
    转发80端口的脚本
  • 原文地址:https://www.cnblogs.com/shamgod/p/5235783.html
Copyright © 2011-2022 走看看