Mastering Spring 5.0
上QQ阅读APP看书,第一时间看更新

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
}