报错信息
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);
声明:该文章由本人自学后记录,仅供参考,如有疏漏 感谢您的指正!谢绝转载!