Spring 知识面面通 之 ContextLoader启动入口源码解析

本文主要是介绍Spring 知识面面通 之 ContextLoader启动入口源码解析,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

  关于Spring的启动入口,在本博《Spring 通篇源码 之 启动 之 程序入口分析》已有介绍,其更多的是在理论层面进行了分析,本文将在源码的角度分析ContextLoaderListener入口。

  源码流程

  以ContextLoaderListener作为入口的启动流程,如图中所示,直到AbstractApplicationContext.refresh(...)进行任务分解,本文仅对左侧部分进行解析,其余部分会在后续博文中进行讲解。

在这里插入图片描述

  源码解析

  1) ContextLoaderListener.contextInitialized(...)

  ① ContextLoaderListener实现了ServletContextListener接口,可以通过contextInitialized(...)contextDestroyed(...)方法接收ServletContext的初始化和销毁事件。

  ② 基于web.xml的应用,需要在web.xml中增加ContextLoaderListener的配置。

<listener><listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener><context-param><param-name>contextConfigLocation</param-name><param-value>classpath*:/spring/applicationContext.xml</param-value>
</context-param>

  ③ 基于Servlet 3.0+版本,可以通过编码的方式对ContextLoaderListener进行配置。

servletContext.addListener(...);

  2) ContextLoader.initWebApplicationContext(...)

  initWebApplicationContext(...)正如方法名描述的一样,主要用来初始化WebApplicationContext,主要涉及操作:

​  ① 校验ServletContext中是否包含WebApplicationContext.class.getName() + ".ROOT"为键的属性,若存在,这抛出异常,以此来禁止重复初始化WebApplicationContext

​  ② 调用createWebApplicationContext(...)用来创建WebApplicationContextcreateWebApplicationContext(...)中调用determineContextClass(...)来确定使用的WebApplicationContext实现类。

  · 首先取得ServletContext初始化参数contextClass,若类可正常加载,则作为WebApplicationContext实现类。

  ·ServletContext未取得初始化参数contextClass或类加载异常,则会使用ContextLoader.properties配置的默认策略指定的实现类。

  ContextLoader.properties文件配置:

org.springframework.web.context.WebApplicationContext=org.springframework.web.context.support.XmlWebApplicationContext

  ③ 若WebApplicationContext实例为ConfigurableWebApplicationContext类型,则调用configureAndRefreshWebApplicationContext(...)配置刷新WebApplicationContext

  ④ 使用WebApplicationContext.class.getName() + ".ROOT"作为键,WebApplicationContext作为值 的键值对设置到ServletContext属性中。

  ⑤ 当前类加载器与加载ContextLoader的类加载器一直时,将WebApplicationContext设置到currentContext属性,否则将WebApplicationContext设置到currentContextPerThread,两种方式的目的都是保证后续操作中可以取到WebApplicationContext

  initWebApplicationContext(...)源码注释:

/*** 根据给定的ServletContext初始化Spring的WebApplicationContext.* 使用构造时给定的提供的ApplicationContext,或者根据contextClass和contextConfigLocation创建一个新的ApplicationContext.* @param servletContext 当前ServletContext.* @return 新的WebApplicationContext.*/
public WebApplicationContext initWebApplicationContext(ServletContext servletContext) {// 从ServletContext获取WebApplicationContext.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");}// WebApplicationContext启动开始时间.long startTime = System.currentTimeMillis();try {// 将上下文存储在本地实例变量中,以确保在ServletContext关闭时它可用.if (this.context == null) {this.context = createWebApplicationContext(servletContext);}// context实现了ConfigurableWebApplicationContext接口.if (this.context instanceof ConfigurableWebApplicationContext) {ConfigurableWebApplicationContext cwac = (ConfigurableWebApplicationContext) this.context;if (!cwac.isActive()) {// 上下文尚未刷新->提供设置父上下文、设置应用程序上下文id等if (cwac.getParent() == null) {// 上下文实例被注入时没有显式的父级.// 确定根web应用程序上下文的父级(如果有).ApplicationContext parent = loadParentContext(servletContext);cwac.setParent(parent);}// 配置、刷新WebApplicationContext.configureAndRefreshWebApplicationContext(cwac, servletContext);}}// 设置this.context设置到ServletContext中.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;}
}

  createWebApplicationContext(...)源码注释:

/*** 实例化此加载程序的根WebApplicationContext,可以是默认上下文类,也可以是自定义上下文类(如果指定的话).* 此实现要求自定义上下文实现ConfigurableWebApplicationContext接口.* 可在子类中重写此方法.* 另外,customizeContext在刷新上下文之前被调用,允许子类对上下文执行自定义修改.* @param sc 当前ServletContext.* @return WebApplicationContext.*/
protected WebApplicationContext createWebApplicationContext(ServletContext sc) {// 确定使用的WebApplicationContext实现类.Class<?> contextClass = determineContextClass(sc);// 若WebApplicationContext实现类未实现ConfigurableWebApplicationContext,则会抛出异常.if (!ConfigurableWebApplicationContext.class.isAssignableFrom(contextClass)) {throw new ApplicationContextException("Custom context class [" + contextClass.getName() +"] is not of type [" + ConfigurableWebApplicationContext.class.getName() + "]");}// 实例化对应WebApplicationContext的实现类.return (ConfigurableWebApplicationContext) BeanUtils.instantiateClass(contextClass);
}

  determineContextClass(...)源码注释:

/*** 返回要使用的WebApplicationContext实现类,可以是默认的XmlWebApplicationContext,也可以是自定义上下文类(如果指定).* @param servletContext 当前ServletContext.* @return 要使用的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);}}// 若未配置ServletContext初始化参数contextClass,//  则使用默认策略,默认策略为org.springframework.web.context.support.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);}}
}

  3) ContextLoader.configureAndRefreshWebApplicationContext(...)

  configureAndRefreshWebApplicationContext(...)主要为WebApplicationContext的刷新进行配置,主要涉及操作:

  ① 若WebApplicationContextid属性认为默认值,则会重新为WebApplicationContext设置一个新值。

  ·ServletContext初始化参数contextId存在,则使用其值作为WebApplicationContextid属性值。

  ·ServletContext初始化参数contextId不存在,则使用WebApplicationContext.class.getName() + ":" + ObjectUtils.getDisplayString(sc.getContextPath())作为WebApplicationContextid属性值。

  ② 将ServletContext实例设置到WebApplicationContextservletContext

  ③ 若ServletContext初始化参数contextConfigLocation存在,则其值为WebApplicationContextconfigLocation的值,内容为WebApplicationContext的配置文件路径。

  ④ 以servletContextInitParams作为键,servletContextInitParamsServletContextServletContextPropertySource实例作为值,设置到环境变量中。

  以servletConfigInitParams作为键,servletConfigInitParamsServletConfigServletConfigPropertySource实例作为值,设置到环境变量中。

  ⑤ 通过ApplicationContextInitializer自定义上下文修改,ApplicationContextInitializer是一个扩展点,可以针对WebApplicationContext进行修改。

  ⑥ 调用WebApplicationContext实例的refresh()方法刷新上下文。

  configureAndRefreshWebApplicationContext(...)源码注释:

/*** 配置、刷新WebApplicationContext.*/
protected void configureAndRefreshWebApplicationContext(ConfigurableWebApplicationContext wac, ServletContext sc) {// 若WebApplicationContext的id仍是其原始默认值,根据可用信息重新设置一个id.if (ObjectUtils.identityToString(wac).equals(wac.getId())) {// 获取ServletContext初始化参数contextId.String idParam = sc.getInitParameter(CONTEXT_ID_PARAM);if (idParam != null) {wac.setId(idParam);}else {// 为WebApplicationContext生成默认id值.wac.setId(ConfigurableWebApplicationContext.APPLICATION_CONTEXT_ID_PREFIX +ObjectUtils.getDisplayString(sc.getContextPath()));}}// ServletContext设置到WebApplicationContext.wac.setServletContext(sc);// 获取ServletContext初始化参数contextConfigLocation.String configLocationParam = sc.getInitParameter(CONFIG_LOCATION_PARAM);// 设置WebApplicationContext的configLocation属性.if (configLocationParam != null) {wac.setConfigLocation(configLocationParam);}// WebApplicationContext环境的initPropertySources将在任何情况下在刷新上下文时被调用.ConfigurableEnvironment env = wac.getEnvironment();if (env instanceof ConfigurableWebEnvironment) {((ConfigurableWebEnvironment) env).initPropertySources(sc, null);}// 通过ApplicationContextInitializer自定义上下文修改.customizeContext(sc, wac);// 刷新上下文.wac.refresh();
}

  总结

  作为Spring框架的主入口,花点时间来研究其原理,还是十分必要的,本文流程解析至ContextLoader.configureAndRefreshWebApplicationContext(...),剩余流程会在后续博文中继续解析。

  源码解析基于spring-framework-5.0.5.RELEASE版本源码。

  若文中存在错误和不足,欢迎指正!

这篇关于Spring 知识面面通 之 ContextLoader启动入口源码解析的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/301715

相关文章

Spring Boot中的路径变量示例详解

《SpringBoot中的路径变量示例详解》SpringBoot中PathVariable通过@PathVariable注解实现URL参数与方法参数绑定,支持多参数接收、类型转换、可选参数、默认值及... 目录一. 基本用法与参数映射1.路径定义2.参数绑定&nhttp://www.chinasem.cnbs

JAVA中安装多个JDK的方法

《JAVA中安装多个JDK的方法》文章介绍了在Windows系统上安装多个JDK版本的方法,包括下载、安装路径修改、环境变量配置(JAVA_HOME和Path),并说明如何通过调整JAVA_HOME在... 首先去oracle官网下载好两个版本不同的jdk(需要登录Oracle账号,没有可以免费注册)下载完

Spring StateMachine实现状态机使用示例详解

《SpringStateMachine实现状态机使用示例详解》本文介绍SpringStateMachine实现状态机的步骤,包括依赖导入、枚举定义、状态转移规则配置、上下文管理及服务调用示例,重点解... 目录什么是状态机使用示例什么是状态机状态机是计算机科学中的​​核心建模工具​​,用于描述对象在其生命

Spring Boot 结合 WxJava 实现文章上传微信公众号草稿箱与群发

《SpringBoot结合WxJava实现文章上传微信公众号草稿箱与群发》本文将详细介绍如何使用SpringBoot框架结合WxJava开发工具包,实现文章上传到微信公众号草稿箱以及群发功能,... 目录一、项目环境准备1.1 开发环境1.2 微信公众号准备二、Spring Boot 项目搭建2.1 创建

Java中Integer128陷阱

《Java中Integer128陷阱》本文主要介绍了Java中Integer与int的区别及装箱拆箱机制,重点指出-128至127范围内的Integer值会复用缓存对象,导致==比较结果为true,下... 目录一、Integer和int的联系1.1 Integer和int的区别1.2 Integer和in

SpringSecurity整合redission序列化问题小结(最新整理)

《SpringSecurity整合redission序列化问题小结(最新整理)》文章详解SpringSecurity整合Redisson时的序列化问题,指出需排除官方Jackson依赖,通过自定义反序... 目录1. 前言2. Redission配置2.1 RedissonProperties2.2 Red

IntelliJ IDEA2025创建SpringBoot项目的实现步骤

《IntelliJIDEA2025创建SpringBoot项目的实现步骤》本文主要介绍了IntelliJIDEA2025创建SpringBoot项目的实现步骤,文中通过示例代码介绍的非常详细,对大家... 目录一、创建 Spring Boot 项目1. 新建项目2. 基础配置3. 选择依赖4. 生成项目5.

JSONArray在Java中的应用操作实例

《JSONArray在Java中的应用操作实例》JSONArray是org.json库用于处理JSON数组的类,可将Java对象(Map/List)转换为JSON格式,提供增删改查等操作,适用于前后端... 目录1. jsONArray定义与功能1.1 JSONArray概念阐释1.1.1 什么是JSONA

Java JDK1.8 安装和环境配置教程详解

《JavaJDK1.8安装和环境配置教程详解》文章简要介绍了JDK1.8的安装流程,包括官网下载对应系统版本、安装时选择非系统盘路径、配置JAVA_HOME、CLASSPATH和Path环境变量,... 目录1.下载JDK2.安装JDK3.配置环境变量4.检验JDK官网下载地址:Java Downloads

nginx -t、nginx -s stop 和 nginx -s reload 命令的详细解析(结合应用场景)

《nginx-t、nginx-sstop和nginx-sreload命令的详细解析(结合应用场景)》本文解析Nginx的-t、-sstop、-sreload命令,分别用于配置语法检... 以下是关于 nginx -t、nginx -s stop 和 nginx -s reload 命令的详细解析,结合实际应