org.springframework.beans.factory.NoUniqueBeanDefinitionException

报错信息


org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type [cn.zzn.spring01.Student] is defined: expected single matching bean but found 2: std1,std2
	at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:312)
	at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:985)

错误代码


public static void main(String[] args) {
        // 1. 创建IOC容器对象
        ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");

        // 2. 利用反射获取bean实例对象
        Student std1 = ac.getBean(Student.class);

        // 3. 打印
        System.out.println(std1);
    }


// applicationContext.xml配置文件
	<bean id="std1" class="cn.zzn.spring01.Student">
        <property name="number" value="1001"></property>
        <property name="name" value="李华"></property>
    </bean>

    <bean id="std2" class="cn.zzn.spring01.Student">
        <property name="number" value="1002"></property>
        <property name="name" value="王明"></property>
    </bean>

错误分析


利用反射获取bean实例对象:Student std1 = ac.getBean(Student.class);
我们希望通过反射得到Student类的对象,
但是明显的在applicationContext.xml配置文件中有两个符合条件的对象

解决方式


// 1. 采用id方式获取bean对象
Student std1 = (Student) ac.getBean("std1");

// 2. 采用id + 反射获取bean对象
Student std1 = (Student) ac.getBean("std2",Student.class);


声明:该文章由本人自学后记录,仅供参考,如有疏漏 感谢您的指正!谢绝转载!

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值