Spring:监听器ContextLoaderListener的作用

在Spring项目时报错:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'demoController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.springdemo.service.DemoDeviceService com.springdemo.controller.DemoController.demoDeviceService; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.springdemo.service.DemoDeviceService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

 

web.xml中配置了:

<context-param>

<param-name>contextConfigLocation</param-name>

<param-value>

classpath:spring.xml,

classpath:spring-hibernate.xml

</param-value>

</context-param>

Tomcat启动日志: No Spring WebApplicationInitializer types detected on classpath​​

 

但是没有配置:

<listener>

<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>

</listener>

配置后后正常

Tomcat启动日志: Initializing Spring root WebApplicationContext

 

Spring提供ServletContentListener的一个实现类ContextLoaderListener监听器,该类可以作为Listener使用,在启动Tomcat容器的时候,该类的作用就是自动装载ApplicationContext的配置信息,如果没有设置contextConfigLocation的初始参数则会使用默认参数WEB-INF路径下的application.xml文件。如果需要自定义读取多个配置文件或者修改默认路径,则可以在web.xml中设置:

<context-param>

    <param-name>contextConfigLocation</param-name>

    <param-value>

          classpath:spring.xml,

          classpath:spring-hibernate.xml

    </param-value>

 

</context-param>

 

ContextLoaderListener会读取这些XML文件并产生 WebApplicationContext对象,然后将这个对象放置在ServletContext的属性

里,这样我们只要可以得到Servlet就可 以得到WebApplicationContext对象,并利用这个对象访问spring 容器管理的bean。

初始成功之后显示如下

信息: Initializing Spring root WebApplicationContext

 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值