传统的SpringMVC项目中,需要在web.xml中配置ContextlistenerContextLoaderListener是负责引导启动和关闭Spring的Root上下文的监听器。主要将处理委托给ContextLoaderContextCleanupListener

类的继承关系。



ContextLoaderListener实现了ServletContextListener接口。该接口主要定义了两个行为:监听上下文创建(contextInitialized)和监听上下文销毁(contextDestroyed)。

ContextLoaderListener只是将方法的处理委托给ContextLoader

package org.springframework.web.context;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener; public class ContextLoaderListener extends ContextLoader implements ServletContextListener { public ContextLoaderListener() {
} public ContextLoaderListener(WebApplicationContext context) {
super(context);
} //初始化Root WebApplication
@Override
public void contextInitialized(ServletContextEvent event) {
//委托给ContextLoader
initWebApplicationContext(event.getServletContext());
} //销毁Root WebApplication
@Override
public void contextDestroyed(ServletContextEvent event) {
//委托给ContextLoader
closeWebApplicationContext(event.getServletContext());
//委托给ContextCleanupListener
ContextCleanupListener.cleanupAttributes(event.getServletContext());
} }

ContextLoaderinitWebApplicationContext方法负责创建root web application context。

//初始化root web application context
public WebApplicationContext initWebApplicationContext(ServletContext servletContext) {
//校验是否已经存在root application,
if (servletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE) != null) {
throw new IllegalStateException(
"Cannot initialize context because there is already a root application context present - " +
"check whether you have multiple ContextLoader* definitions in your web.xml!");
} Log logger = LogFactory.getLog(ContextLoader.class);
servletContext.log("Initializing Spring root WebApplicationContext");
if (logger.isInfoEnabled()) {
logger.info("Root WebApplicationContext: initialization started");
}
long startTime = System.currentTimeMillis(); try {
// Store context in local instance variable, to guarantee that
// it is available on ServletContext shutdown.
//创建WebApplicationContext,并保存到变量中,等关闭时使用
if (this.context == null) {
this.context = createWebApplicationContext(servletContext);
}
//如果是ConfigurableWebApplicationContext,则配置上下文并刷新
if (this.context instanceof ConfigurableWebApplicationContext) {
ConfigurableWebApplicationContext cwac = (ConfigurableWebApplicationContext) this.context;
if (!cwac.isActive()) {
// The context has not yet been refreshed -> provide services such as
// setting the parent context, setting the application context id, etc
if (cwac.getParent() == null) {
// The context instance was injected without an explicit parent ->
// determine parent for root web application context, if any.
ApplicationContext parent = loadParentContext(servletContext);
cwac.setParent(parent);
}
configureAndRefreshWebApplicationContext(cwac, servletContext);
}
}
//在ServletContext中设置属性,表明已经配置了root web application context
servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, this.context); ClassLoader ccl = Thread.currentThread().getContextClassLoader();
if (ccl == ContextLoader.class.getClassLoader()) {
currentContext = this.context;
}
else if (ccl != null) {
currentContextPerThread.put(ccl, this.context);
} if (logger.isDebugEnabled()) {
logger.debug("Published root WebApplicationContext as ServletContext attribute with name [" +
WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE + "]");
}
if (logger.isInfoEnabled()) {
long elapsedTime = System.currentTimeMillis() - startTime;
logger.info("Root WebApplicationContext: initialization completed in " + elapsedTime + " ms");
} return this.context;
}
catch (RuntimeException ex) {
logger.error("Context initialization failed", ex);
servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, ex);
throw ex;
}
catch (Error err) {
logger.error("Context initialization failed", err);
servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, err);
throw err;
}
}

该方法主要分为四步:

  1. 校验是否已经存在root WebApplicationContext
  2. 创建root WebApplicationContext
  3. 配置上下文并刷新
  4. 绑定root WebApplicationContext到servlet context上

这四步具体分析如下:

1.校验

校验的过程比较简单,主要是判断Servlet Context是否已经绑定过WebApplicationContext

2.创建对象

createWebApplicationContext()方法负责创建WebApplicationContext对象,主要过程是确定WebApplicationContext类,并实例化:

	protected WebApplicationContext createWebApplicationContext(ServletContext sc) {
//查找WebApplicationContext的类
Class<?> contextClass = determineContextClass(sc);
if (!ConfigurableWebApplicationContext.class.isAssignableFrom(contextClass)) {
throw new ApplicationContextException("Custom context class [" + contextClass.getName() +
"] is not of type [" + ConfigurableWebApplicationContext.class.getName() + "]");
}
//实例化对象
return
(ConfigurableWebApplicationContext) BeanUtils.instantiateClass(contextClass);
}

决定WebApplicationContext类的主要策略是先判断ServletContext是否配置了contextClass属性,如果是,则用该属性指定的类作为WebApplicationContext类,否则则是否默认策略。默认策略是根绝classpath下的ContextLoader.properties中配置的类作为WebApplicatioNCOntext类:

protected Class<?> determineContextClass(ServletContext servletContext) {
//优先根据servletContext配置的contextClass属性
String contextClassName = servletContext.getInitParameter(CONTEXT_CLASS_PARAM);
if (contextClassName != null) {
try {
return ClassUtils.forName(contextClassName, ClassUtils.getDefaultClassLoader());
}
catch (ClassNotFoundException ex) {
throw new ApplicationContextException(
"Failed to load custom context class [" + contextClassName + "]", ex);
}
}
//在通过classpath下的`ContextLoader.properties`文件制定的类作为WebApplicationContext类
//默认是XmlWebApplicationContext
else {
contextClassName = defaultStrategies.getProperty(WebApplicationContext.class.getName());
try {
return ClassUtils.forName(contextClassName, ContextLoader.class.getClassLoader());
}
catch (ClassNotFoundException ex) {
throw new ApplicationContextException(
"Failed to load default context class [" + contextClassName + "]", ex);
}
}
}
配置与刷新

创建WebApplicationContext对象后,ContextLoader会判断是否是ConfigurableWebApplicationContext

ConfigurableWebApplicationContext拓展了WebApplicationContext的能力。其不仅扩展了自身方法,还继承了ConfigurableApplicationContext接口。

配置与刷新的步骤也正是利用了这些接口提供的能力。

	//配置并刷新上下文
protected void configureAndRefreshWebApplicationContext(ConfigurableWebApplicationContext wac, ServletContext sc) {
//设置ID
if (ObjectUtils.identityToString(wac).equals(wac.getId())) {
// The application context id is still set to its original default value
// -> assign a more useful id based on available information
String idParam = sc.getInitParameter(CONTEXT_ID_PARAM);
if (idParam != null) {
wac.setId(idParam);
}
else {
// Generate default id...
wac.setId(ConfigurableWebApplicationContext.APPLICATION_CONTEXT_ID_PREFIX +
ObjectUtils.getDisplayString(sc.getContextPath()));
}
} //WebApplicationContext绑定Servlet Context
wac.setServletContext(sc);
String configLocationParam = sc.getInitParameter(CONFIG_LOCATION_PARAM);
if (configLocationParam != null) {
wac.setConfigLocation(configLocationParam);
} // The wac environment's #initPropertySources will be called in any case when the context
// is refreshed; do it eagerly here to ensure servlet property sources are in place for
// use in any post-processing or initialization that occurs below prior to #refresh
ConfigurableEnvironment env = wac.getEnvironment();
if (env instanceof ConfigurableWebEnvironment) {
((ConfigurableWebEnvironment) env).initPropertySources(sc, null);
} //自定义上下文初始过程,留给用户的拓展机制
customizeContext(sc, wac);
//刷新上下文,加载bean
wac.refresh();
}

创建流程图如下:

SpringMVC Root WebApplicationContext启动流程的更多相关文章

  1. SpringMVC源码解析-DispatcherServlet启动流程和初始化

    在使用springmvc框架,会在web.xml文件配置一个DispatcherServlet,这正是web容器开始初始化,同时会在建立自己的上下文来持有SpringMVC的bean对象. 先从Dis ...

  2. 项目tomcat启动停在Initializing Spring root WebApplicationContext

    来源于:http://ourteam.iteye.com/blog/1270699 某日,再次启动项目,spring一直停在这一句: Initializing Spring root WebAppli ...

  3. 关于Tomcat启动时,长时间停在Initializing Spring root webApplicationContext处的原因

    1.大家肯定经常会遇到这样的问题,以前启动tomcat都不会出问题.现在一起动就会卡到Initializing Spring root webApplicationContext处,tomcat会报连 ...

  4. tomcat启动时非常慢,启动时 一直卡在Root WebApplicationContext: initialization completed(转)

    转载地址:https://www.cnblogs.com/youxin/p/8793554.html 使用方式: JAVA_OPTS="-Djava.awt.headless=true -D ...

  5. tomcat启动时非常慢,启动时 一直卡在Root WebApplicationContext: initialization completed

    每次重启自己的服务tomcat都需要卡住很长时间,每次都是日志停在 Root WebApplicationContext: initialization completed in 744 ms这个地方 ...

  6. 启动web项目卡在Initializing Spring root WebApplicationContext不动

    这几天在和同学一起做一个电教器材管理系统的Web项目,用SVN互通,在此记录下经常遇到的bug. Bug: 启动项目一直卡在Initializing Spring root WebApplicatio ...

  7. Tomcat 启动卡在 Root WebApplicationContext: initialization completed in

    tomcat 启动一直卡在 Root WebApplicationContext: initialization completed in 重启了很多次,更换jdk版本,tomcat版本都不行. to ...

  8. Spring基础系列-容器启动流程(1)

    原创作品,可以转载,但是请标注出处地址:https://www.cnblogs.com/V1haoge/p/9870339.html 概述 ​ 我说的容器启动流程涉及两种情况,SSM开发模式和Spri ...

  9. Spring MVC启动流程分析

    本文是Spring MVC系列博客的第一篇,后续会汇总成贴子. Spring MVC是Spring系列框架中使用频率最高的部分.不管是Spring Boot还是传统的Spring项目,只要是Web项目 ...

随机推荐

  1. K:leetcode 5381.查询带键的排列 这题简单,但我还能优化。精益求精,才是算法的乐趣所在!

    前言: 本题来自leetcode第184场周赛的第二小题.以前参加过周赛,觉得很有趣.苦于最近一段时间比较忙就没坚持参加了(实际上是借口来着....),由于昨晚思考一些事情,导致睡不着,所以起得有点早 ...

  2. egg.js部署到服务器

    关于egg.js项目部署服务器的问题 我使用的是腾讯云centos , 部署前需要确保服务器上安装了mysql, node . mysql下载:https://dev.mysql.com/downlo ...

  3. MTK Androiod HAL如何向上层提供接口

    Android中HAL如何向上层提供接口总结 转自:http://blog.csdn.net/flydream0/article/details/7086273 参考文献: http://blog.c ...

  4. Linux网络安全篇,进入SELinux的世界(三)

    SELinux防火墙配套的服务 一.auditd 1.基本功能 将详细信息写入到 /var/log/audit/audit.log文件 2.设置开机自动启动 chkconfig --list audi ...

  5. Github 骚操作

    GitHub 竟然有这些骚操作,真是涨姿势 GitHub,不用过多介绍.一个面向开源及私有软件项目的托管平台,因为只支持 git 作为唯一的版本库格式进行托管,故名 GitHub. 作为「全球最大的程 ...

  6. PHP程序员的能力水平层次(一)

    前言 之前看过很多篇关于服务端工程师和PHP开发者的能力模型介绍,每篇都对能力有侧重点. 下面我们来详细谈谈以开发能力为基准点的PHP程序员的能力水平层次. 层层递进 1.功能开发 这个水平的程序员一 ...

  7. hadoop(十一)HDFS简介和常用命令介绍

    HDFS背景 随着数据量的增大,在一个操作系统中内存不了了,就需要分配到操作系统的的管理磁盘中,但是不方便管理者维护,迫切需要一种系统来管理多态机器上的文件,这就是分布式文件管理系统. HDFS的概念 ...

  8. go中内存泄露的发现与排查

    一,什么是内存泄漏 Go 中的并发性是以 goroutine(独立活动)和 channel(用于通信)的形式实现的.处理 goroutine 时,程序员需要小心翼翼地避免泄露.如果最终永远堵塞在 I/ ...

  9. Julia基础语法字符和字符串

    1.Julia字符串  2.字符

  10. 在数组添加元素时报错:IndexError: list index out of range

    今天第一次发随笔还有许多不足之处,欢迎评论!!! 最近在写一个成语接龙的小游戏,结果在数组添加元素时报错:IndexError: list index out of range 源码: import ...