ContextLoaderListener的作用详解

每一个整合spring框架的项目中,总是不可避免地要在web.xml中加入这样一段配置

<!--  通过配置上下文参数,使得服务器一启动就加载ssm整合配置文件和spring的事物管理配置文件-->
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:spring-persist-*.xml</param-value>
  </context-param>

  <!--    配置了监听器-->
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>

而这段配置有什么作用,或者说ContextLoaderListener到底有什么作,首先从ContextLoaderListener源码入手。

public class ContextLoaderListener extends ContextLoader implements ServletContextListener

ContextLoaderListener继承自ContextLoader,实现的是ServletContextListener接口。

继承ContextLoader有什么作用?

ContextLoader通过完成实际的WebApplicationContext,来完成Ioc容器的初始化工作。注意,ApplicationContext是专门为Web应用准备的,它允许从相对于Web根目录的路径中装载配置文件完成初始化。所以ContextLoaderListener可以指定在Web应用程序启动时载入Ioc容器,这正是通过ContextLoader来实现的

实现ServletContextListener又有什么作用?

ServletContextListener接口里的函数会结合Web容器的生命周期被调用。因为ServletContextListener是ServletContext的监听者,如果ServletContext发生变化,会触发相应的事件,而监听器一直对事件监听,如果接收到了变化,就会做出预先设计好的相应动作。由于ServletContext变化而触发的监听器的响应具体包括:在服务器启动时,ServletContext被创建的时候,服务器关闭时,ServletContext将被销毁的时候等。

ContextLoaderListener作用总结

ContextLoaderListener的作用就是启动Web容器时,读取在contextConfigLocation中定义的xml文件,自动装配ApplicationContext的配置信息,并产生WebApplicationContext对象,然后将这个对象放置在ServletContext的属性里,这样我们只要得到Servlet就可以得到WebApplicationContext对象,并利用这个对象访问spring容器管理的bean。
简单来说,就是上面这段配置为javaweb项目提供了spring支持,初始化了Ioc容器。

猜你喜欢

转载自blog.csdn.net/wwwwwww31311/article/details/113769949