- Mastering Spring 5.0
- Ranga Rao Karanam
- 105字
- 2021-07-02 22:12:07
The @Qualifier annotation
The @Qualifier annotation can be used to give a reference to a Spring bean. The reference can be used to qualify the dependency that needs to be autowired.
In the case of the following example, there are two sorting algorithms available: QuickSort and MergeSort. But since @Qualifier("mergesort") is used in the SomeService class, MergeSort, which also has a mergesort qualifier defined on it, becomes the candidate dependency selected for autowiring:
@Component
@Qualifier("mergesort")
class MergeSort implements SortingAlgorithm {
// Class code here
}
@Component
class QuickSort implements SortingAlgorithm {
// Class code here
}
@Component
class SomeService {
@Autowired
@Qualifier("mergesort")
SortingAlgorithm algorithm;
}