Spring抛出NoUniqueBeanDefinitionException异常和NoSuchBeanDefinitionException
1.NoUniqueBeanDefinitionException异常
注意:根据 类型获取bean时,要求IOC容器中有且只有一个类型匹配的bean。若我们使用xml配置的bean,导致此异常可能是配置了多个bean,如下:
<bean id="userController" class="com.b0.spring.controller.UserController" autowire="byType">
</bean>
<bean id="userService" class="com.b0.spring.service.impl.UserServiceImpl" autowire="byType">
</bean>
<bean id="service" class="com.b0.spring.service.impl.UserServiceImpl" autowire="byType">
</bean>
测试类使用
ApplicationContext IOC = new ClassPathXmlApplicationContext("spring-autowire-xml.xml");
UserController bean = IOC.getBean(UserController.class);
因为我们在xml中使用的自动装配是根据类型匹配,此处会匹配到多个bean无法确定,抛出bean不唯一异常,解决方案:去重复的service bean此处去除后为:
<bean id="userController" class="com.b0.spring.controller.UserController" autowire="byType">
</bean>
<bean id="userService" class="com.b0.spring.service.impl.UserServiceImpl" autowire="byType">
</bean>
</bean>
2. NoSuchBeanDefinitionException异常,bean装配中NullPointerException空指针异常
若没有任何一个类型匹配的bean,会抛出异常NoSuchBeanDefinitionException
或者NullPointerException,说明你的bean依赖(赋值)没有配置,未找到,补充全即可
例如:下方案例采用MVC架构,笔者注释了controller的自配类型匹配数据,会抛出空指针异常
<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="userController" class="com.b0.spring.controller.UserController" autowire="byType">
<!-- <property name="userService" ref="userService"></property>-->
</bean>
<!-- <bean id="service" class="com.b0.spring.service.impl.UserServiceImpl" autowire="byType">-->
<!-- <!– <property name="userDao" ref="userDao"></property>–>-->
<!-- </bean>-->
<bean id="userDao" class="com.b0.spring.dao.impl.UserDaoImpl"></bean>
</beans>
解决方案:补充全controller的类型依赖即可