• [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

  • 相关阅读:
    Top Things to Consider When Troubleshooting Complex Application Issues
    compiler
    .net 开源相关
    windows快捷键
    NETMON& Message Analyzer
    Articles Every Programmer Must Read
    cluster,network
    SQL Debugging
    【重要】接口测试----必知常见问题解答(面试常会被问到)
    python+requests----登录接口reponse中token传递给其他接口使用的一个简单小示例介绍
  • 原文地址:https://www.cnblogs.com/Answer1215/p/10656452.html
Copyright © 2020-2023  润新知