Spring进阶(六)之Primary用法

案例一:

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属性,不然如果有多个候选者,容器照样会懵逼,不知道该如何选择

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

冰魄雕狼

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值