1. 程式人生 > >[Spring boot] Autowired by name, by @Primary or by @Qualifier

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

nta side autowire result rim vat public fff have

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