• [Spring boot] Autowired by name, by @Primary or by @Qualifier


    In the example we have currently:

    @Component
    public class BinarySearchImpl {
    
        @Autowired
        private SortAlgo sortAlgo;
    
        public int binarySearch(int [] numbers, int target) {
            // Sorting an array
    
            sortAlgo.sort(numbers);
            System.out.println(sortAlgo);
            // Quick sort
    
            // Return the result
            return 3;
        }
    
    }
    @Component
    @Primary
    public class QuickSortAlgo implements SortAlgo{
        public int[] sort(int[] numbers) {
            return numbers;
        }
    }
    
    @Component
    public class BubbleSortAlgo implements SortAlgo{
        public int[] sort(int[] numbers) {
            return numbers;
        }
    }

    The way we do Autowired is by '@Primary' decorator. 

    It is clear that one implementation detail is the best, then we should consider to use @Primary to do the autowiring

    Autowiring by name

    It is also possible to autowiring by name:

        
    // Change From
    @Autowired
     private SortAlgo sortAlgo;
    
    // Change to
    @Autowired
    private SortAlgo quickSortAlgo

    We changed it to using 'quickSortAlgo', even we remove the @Primary from 'QuickSortAlgo', it still works as the same.

    @Component
    // @Primary
    public class QuickSortAlgo implements SortAlgo{
        public int[] sort(int[] numbers) {
            return numbers;
        }
    }

    @Qualifier('')

    Instead of using naming, we can use @Qualifier() to tell which one we want to autowired.

    @Component
    @Primary
    @Qualifier("quick")
    public class QuickSortAlgo implements SortAlgo{
        public int[] sort(int[] numbers) {
            return numbers;
        }
    }
    
    
    @Component
    @Qualifier("bubble")
    public class BubbleSortAlgo implements SortAlgo{
        public int[] sort(int[] numbers) {
            return numbers;
        }
    }
    @Autowired
    @Qualifier("bubble")
    private SortAlgo sortAlgo;

    In this case, it will use 'BubbleSortAlgo'. 

    So we can say that

    @Qualifier > @Primary > @naming

  • 相关阅读:
    MS SQL数据类型
    ASP中调用存储过程、语法、写法-sql server数据库
    系統存儲過程System stored procedures
    ASP调用带参数存储过程的几种方式
    解密SQLSERVER2000存储过程,函数,视图,触发器
    SQL Script 執行的時間
    各種正則表达式示例
    12款操作系统安装全程图解(菜鸟必备宝典)
    内存 : DDR2与DDR
    數據庫分頁
  • 原文地址:https://www.cnblogs.com/Answer1215/p/10656452.html
Copyright © 2020-2023  润新知