The @Primary annotation

When the @Primary annotation is used on a bean, it becomes the primary one to be used when there is more than one candidate available to autowire a specific dependency.

In the case of the following example , there are two sorting algorithms available: QuickSort and MergeSort. If the component scan finds both of them, QuickSort is used to wire any dependencies on SortingAlgorithm because of the @Primary annotation:

    interface SortingAlgorithm {     }     @Component     class MergeSort implements SortingAlgorithm {       // Class code here     }    @Component    @Primary    class QuickSort implements SortingAlgorithm {      // Class code here    }

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.