![[Spring boot] Autowired by name, by @Primary or by @Qualifier [Spring boot] Autowired by name, by @Primary or by @Qualifier](https://image.shishitao.com:8440/aHR0cHM6Ly9ia3FzaW1nLmlrYWZhbi5jb20vdXBsb2FkL2NoYXRncHQtcy5wbmc%2FIQ%3D%3D.png?!?w=700&webp=1)
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