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

Posted Answer1215

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[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

 

以上是关于[Spring boot] Autowired by name, by @Primary or by @Qualifier的主要内容,如果未能解决你的问题,请参考以下文章

spring boot filter -Autowired

如何在 Spring Boot 类之间正确注入 @Autowired?

spring-boot Autowired DiscoveryClient RestTemplate UnknownHostException

单元测试中的 Spring Boot @Autowired 返回 NullPointerException

其他模块中的 Spring Boot MongoDB 存储库不是 @Autowired

如何在spring boot的多个类中使用@Autowired MongoTemplate