BUG——Error creating bean

项目场景:

一个用SSM写的web项目,用spring集成了mybatis

问题描述:

项目成功跑起,但控制台报错如下:

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'loginController': Unsatisfied dependency expressed through field 'userInfoService'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'sysUserInfoService': Unsatisfied dependency expressed through field 'baseMapper'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'dao.SysUserInfoDao' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

分析以及解决:

      根据报错原因可知是当通过@Autowired自动创建对象的时候,在spring容器中未找到对应的对象
      检查了各种配置和注解,发现配置和注解都没问题。既然这些都没问题,也就是对应的bean都会放入容器中,那为什么还是找不到对应的bean呢,我突然想到是不是spring容器根本没创建啊?
      果不其然,发现web,xml中未配置监听器ContextLoaderListener ,无法自动创建spring容器。于是赶紧将其配置好,再次启动项目,没有报错,成功解决!
 <!--注册监听器ContextLoaderListener-->
   <listener>
       <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
   </listener>
   <context-param>
       <param-name>contextConfigLocation</param-name>
       <param-value>classpath:spring.xml</param-value>
   </context-param>

原因总结:

       在web.xml中配置ContextLoaderListener的作用:ContextLoaderListener实现了ServletContextListener接口,所以会有两个方法contextInitialized和contextDestroyed。服务器启动时会自动调用方法contextInitialized,在这个方法中会声明创建spring容器(并将其放入全局作用域中)
       之前未配置ContextLoaderListener导致无法自动创建spring容器,压根就没有spring容器,也就无法获得spring容器中的bean,所以@Autowired自动注入就找不到对应的bean,也就会报错啦.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值