案例一:
public interface IService {
}
public class Service1 implements IService{
}
public class Service2 implements IService{
}
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="service1" class="com.example.Bean.Service1"></bean>
<bean id="service2" class="com.example.Bean.Service2"></bean>
</beans>
@Test
void contextLoads() {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
IService bean = context.getBean(IService.class);
System.out.println(bean);
}
测试以后报错:
案例二:
public interface IService {
}
public class Service1 implements IService{
}
public class Service2 implements IService{
}
public class testBean {
private IService iService;
public void setiService(IService iService) {
this.iService = iService;
}
}
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="service1" class="com.example.Bean.Service1"></bean>
<bean id="service2" class="com.example.Bean.Service2"></bean>
<!--根据类型自动注入-->
<bean id="testBean" class="com.example.Bean.testBean" autowire="byType"></bean>
</beans>
测试以后还是报了一样的错误:
上面两个案例报错的原因: 当希望从容器中获取到一个bean对象的时候,容器中却找到了多个匹配的bean,此时spring不知道如何选择了,处于懵逼状态,就会报这个异常。
Primary
spring中可以通过bean元素的primary属性来解决这个问题,可以通过这个属性来指定当前bean为主要候选者,当容器查询一个bean的时候,如果容器中有多个候选者匹配的时候,此时spring会返回主要的候选者。
我们在上面案例的基础上,给被注入的冲突的bean的其中一个加上primary属性
这样就解决了多个bean匹配导致的异常,但是也要注意,这些冲突的bean中,只能有一个bean添加primary属性,不然如果有多个候选者,容器照样会懵逼,不知道该如何选择