Spring报错:
Exception in thread “main” org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type [com.atguigu.spring.mod.Person] is defined: expected single matching bean but found 2: person,persontwo
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:312)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:985)
at com.atguigu.spring.mod.TestBySpring.main(TestBySpring.java:13)
expected single matching bean but found 2:
这里由于使用Class获取对象时,xml文件管理的对应的类型对象有多个,导致报错,
所以使用
Person person = ac.getBean(Person.class);
此方法获取对象时,要求spring所管理的此类型的对象只能有一个
总结:从IOC容器中获取bean时,除了通过id值获取,还可以通过bean的类型获取。但如果同一个类型的bean在XML文件中配置了多个,则获取时会抛出异常,所以同一个类型的bean在容器中必须是唯一的。