Spring-web源码解析之ContextLoaderListener

基于版本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开头的类,进行各自定义的销毁流程。












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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值