大家可能注意到,刚才的代码。

我们并没有使用@Component去注解快速排序的那个类。

@Component
public class QuickSortAlgorithm implements SortAlgorithm {}

如果我们给他添加上@Component会怎么样呢?

现在,我们对SortAlgorithm接口就有了两个实现

  • BubbleSortAlgorithm
  • QuickSortAlgorithm

让我们来执行以下程序

***************************
APPLICATION FAILED TO START
***************************

Description:

Parameter 0 of constructor in con.demo.BinarySearchImpl required a single bean, but 2 were found:
	- bubbleSortAlgorithm: defined in file [/Users/jundongpei/resource/repo/Spring-tutorial/step_06/target/classes/con/demo/BubbleSortAlgorithm.class]
	- quickSortAlgorithm: defined in file [/Users/jundongpei/resource/repo/Spring-tutorial/step_06/target/classes/con/demo/QuickSortAlgorithm.class]


Action:

Consider marking one of the beans as @Primary, updating the consumer to accept multiple beans, or using @Qualifier to identify the bean that should be consumed

给大家介绍一个新的注解@Primary

当Spring就不知道你注入哪个,那现在就可以通过下面两个办法解决:

  • @Primary 优先考虑,优先考虑被注解的对象注入。
  • @Qualifier 名字声明,声明后对名字进行使用。我们一会讲到。