zoukankan      html  css  js  c++  java
  • Spring 注解之@Primary注解

      当一个接口有多个不同实现类时,使用注解@Autowired时会报
    org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type [xxxx] is defined: expected single matching bean but found 2:xxx1,xxx2异常信息,意思是
    Spring 发现两个类型相同的bean,无法根据类型选择装配哪一个。这时候就可以使用@Primary注解设置默认bean,使得项目启动时只装配其中一种bean。

      @Primary:在众多相同的Bean中,优先使用@Primary注解的Bean。

    方案1-@Qualifier

      @Qualifier注解用于细粒度地根据bean名称选择bean候选者,是遇到多个相同类型bean时比较常用的解决方案。注解@Autowired 默认是根据类型来自动注入bean,结合 @Qualifier使用时,自动注入的策略就从 byType 转变成 byName 了。

    方案2-@Primary

      @Primary可以理解为,装配bean的时候优先选择使用@Primary注解的Bean。相同类型的bean不可以同时设置多个@Primary注解。内部实质是设置BeanDefinition的primary属性。

    @Primary案例分析

      以在某个相同类型的bean上添加注解@Primary为案例进行分析。测试用例中,Shape接口类有三个实现类。

    /**
     * 定义bean接口
     */
     public interface Shape {
       void draw();
    }
    
    =========== 我是分割线 =============
    @Primary
    @Service
    public class Rectangle implements Shape {
     
       @Override
       public void draw() {
          System.out.println("Inside Rectangle::draw() method.");
       }
    }
    =========== 我是分割线 =============
    @Service
    public class Square implements Shape {
     
       @Override
       public void draw() {
          System.out.println("Inside Square::draw() method.");
       }
    }
    =========== 我是分割线 =============
    @Service
    public class Circle implements Shape {
     
       @Override
       public void draw() {
          System.out.println("Inside Circle::draw() method.");
       }
    }
    

    因为实现类 Rectangle 被注解@Primary修饰,所以它将优先被装配到接口类 Shape。有了上面的代码之后,我们控制层编写如下测试用例:

        //  优先装配名字为rectangle的bean
        @Autowired
        private Shape shape;
        
        @GetMapping("/drawByPrimary")
        public String drawByPrimary() {
            shape.draw();
            return "成功";
        }
    

    结束语

      以上就是这篇文章的全部内容了,希望本文对大家的学习或者工作能带来一定的帮助,如有疑问请留言交流。Wiener在此祝各位生活愉快!工作顺利!


      读后有收获,小礼物走一走,请作者喝咖啡。

    赞赏支持

  • 相关阅读:
    高校招生说明网页被挂马 考生浏览需谨慎 狼人:
    匹配情况hdu4451Dressing
    方法springBean Lifecycle in Spring
    android颜色关于Android TabHost切换Tab字体的颜色背景颜色改变
    推荐美国简单的选项卡功能实现
    按钮function关闭子页面刷新父页面中部分控件数据
    编码文件AndroidStudio初体验:解决Execution failed for task ':TestAndroid:compileDebug'.
    图片类关于实现图片剪切功能的相关类的学习心得
    nullnull10879 Code Refactoring
    java独立HDU 2845 Beans
  • 原文地址:https://www.cnblogs.com/east7/p/14390843.html
Copyright © 2011-2022 走看看