5.spring系列- primary使用

案例

public class NormalBean {

    public interface IService{}
    
    public static class ServiceA implements IService{}
    
    public static class ServiceB implements IService{}
}

bean xml配置:

    <bean id="serviceA" class="com.spring.beanPrimary.NormalBean$ServiceA"/>

    <bean id="serviceB" class="com.spring.beanPrimary.NormalBean$ServiceB"/>

测试:

@Test
    public void beanPrimary() {
        String path = "classpath:/bean/beansPrimary.xml";
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(path);
        NormalBean.IService bean = context.getBean(NormalBean.IService.class);
        System.out.println(bean);
    }

输出:

...
org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type 'com.spring.beanPrimary.NormalBean$IService' available: expected single matching bean but found 2: serviceA,serviceB
...

spring容器中定义了2个bean,分别是serviceA和serviceB,这两个bean对象都实现了IService接口,而用例中我们想从容器中获取IService接口对应的bean,此时容器中有2个候选者(serviceA和serviceB)满足我们的需求,此时spring容器不知道如何选择

下面我们使用primary来解决上面案例的问题:

直接修改xml配置:

    <bean id="serviceA" class="com.spring.beanPrimary.NormalBean$ServiceA" primary="true"/>

    <bean id="serviceB" class="com.spring.beanPrimary.NormalBean$ServiceB"/>

运行看结果:

com.spring.beanPrimary.NormalBean$ServiceA@449a4f23

当从容器中查找一个bean的时候,如果容器中出现多个Bean候选者时,可以通过primary="true"将当前bean置为首选者,那么查找的时候就会返回主要的候选者,否则将抛出异常。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值