Spring-web源码解析之ContextLoaderListener

简介: 基于版本4.1.7.RELEASE该类作用:ContextLoaderListener作为启动时的监听器,用于开启和关闭Spring的根WebApplicationContext,该监听器在web.

基于版本4.1.7.RELEASE

该类作用:ContextLoaderListener作为启动时的监听器,用于开启和关闭Spring的根WebApplicationContext,该监听器在web.xml中应该放置于org.springframework.web.util.Log4jConfigListener 后面

先看看它的父类和实现的接口 

继承ContextLoader : 应用上下文初始化的实际执行者

实现ServletContextListener :  接收ServletContext生命周期变化时的通知

构造函数:

public ContextLoaderListener() {
}

在web.xml中如下方式定义ContextLoaderListener的时候会被默认调用:

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

在创建ContextLoaderListener的时候,会根据servlet中指定的contextClass和contextConfigLocation来创建web application context,具体的工作则是在ContextLoader中进行

创建的ApplicationContext会被挂到WebApplicationContext的ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE属性上。

带参数的构造函数:

public ContextLoaderListener(WebApplicationContext context) {
   super(context);
}

指定WebApplicationContext,同样它也会被挂到ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE属性上。

传入的context是否加载完成配置文件,即是否被refresh的状态是未定的,如果 context是ConfigurableWebApplicationContext类型并且未被refresh,则会根据状态产生以下5种行为。

  1. 根据是否具有id,赋值一个id。
  2. ServletContext和ServletConfig会被委派给context进行代理。
  3. 调用customizeContexxt方法
  4. 通过contextInitializerClasses指定的任意ApplicationContextInitializer会被接受
  5. 调用refresh方法

如果不满足上述行为产生的条件,则默认为用户已经完成所需要做的工作。

@Override
public void contextInitialized(ServletContextEvent event) {
   initWebApplicationContext(event.getServletContext());
}

实现ServletContextListener中的方法,属于ServletContext的生命周期中开始初始化时通知的事件,我们查看ServletContextListener中对于该方法的解释:

/**
 * Receives notification that the web application initialization
 * process is starting.
 */

意思是在web application 初始化进程开始的时候会接收到通知,但是方法名是contextInitialized过去式,那到底是开始初始化的时候通知还是初始化完毕再通知呢?我们看对于参数的解释

/**
* @param sce the ServletContextEvent containing the ServletContext
* that is being initialized
*/

参数中包含已经被初始化完毕的ServletContext,表示接收通知时,web application 应该是被初始化完毕了。所有的servlet和filter是在该通知发出后才被初始化的

回到@Override这里调用了ContextLoader的initWebApplicationContext方法,表明在WebApplicationContext初始化完毕后才开始RootApplicationContext的初始化工作。

@Override
public void contextDestroyed(ServletContextEvent event) {
   closeWebApplicationContext(event.getServletContext());
   ContextCleanupListener.cleanupAttributes(event.getServletContext());
}

同样是实现ServletContextListener中的方法,在ServletContextListener的接口方法定义中,该方法是ServletContext关闭时通知的,在任何一个listener被通知到之前,所有的servlets和filters会被销毁,参数event中含有已经被销毁的ServletContext。

回到@Override方法中,这里调用了ContextLoader的closeWebApplicationContext方法,并且调用了ContextCleanupListener的cleanupAttributes清理方法,这里面会查找到所有org.springframework开头的类,进行各自定义的销毁流程。












目录
相关文章
|
17天前
|
XML Java Android开发
Android实现自定义进度条(源码+解析)
Android实现自定义进度条(源码+解析)
49 1
|
21天前
|
存储 NoSQL 算法
【Redis技术进阶之路】「底层源码解析」揭秘高效存储模型与数据结构底层实现(字典)(二)
【Redis技术进阶之路】「底层源码解析」揭秘高效存储模型与数据结构底层实现(字典)
34 0

推荐镜像

更多