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 ...

Get Mastering Spring 5.0 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.