Spring NoUniqueBeanDefinitionException异常和NoSuchBeanDefinitionException

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">-->
<!--        &lt;!&ndash;        <property name="userDao" ref="userDao"></property>&ndash;&gt;-->
<!--    </bean>-->
    <bean id="userDao" class="com.b0.spring.dao.impl.UserDaoImpl"></bean>
</beans>

解决方案:补充全controller的类型依赖即可

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值