Spring源码情操陶冶-ContextLoader
前言-阅读源码有利于陶冶情操,本文承接前文Spring源码情操陶冶-ContextLoaderListener
静态代码块内容
ContextLoader在被主动调用的时候,会执行其的一个静态块,代码如下
static {
// Load default strategy implementations from properties file.
// This is currently strictly internal and not meant to be customized
// by application developers.
try {
//这里DEFAULT_STRATEGIES_PATH值为ContextLoader.properties
ClassPathResource resource = new ClassPathResource(DEFAULT_STRATEGIES_PATH, ContextLoader.class);
//这里的loadProperties方法其实调用的getClass().getResourceAsStream(path)方法
//其是从当前包路径下查找相应的资源,点开相应的class路径,果不其然ContextLoader.properties与ContextLoader.class在同一目录下
defaultStrategies = PropertiesLoaderUtils.loadProperties(resource);
}
catch (IOException ex) {
throw new IllegalStateException("Could not load 'ContextLoader.properties': " + ex.getMessage());
}
}
具体的解析功能见注释,上面分析到其会读取ContextLoader.properties,这个文件下只有一个属性:
org.springframework.web.context.WebApplicationContext=org.springframework.web.context.support.XmlWebApplicationContext
由此可见其最有可能是通过
XmlWebApplicationContext类来进行相应的web上下文初始化
初始化方法initWebApplicationContext
从前文得知,ContextLoaderListener会调用ContextLoader#initWebApplicationContext(ServletContext context)方法来创建web application上下文环境,代码清单如下
//首先判断有无org.springframework.web.context.WebApplicationContext.ROOT属性,不允许已有
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.
if (this.context == null) {
//创建方法,一般会创建前点所述的XmlWebApplicationContext
this.context = createWebApplicationContext(servletContext);
}
//XmlWebApplicationContext是ConfigurableWebApplicationContext的实现类,指定的contextClass应该是ConfigurableWebApplicationContext的实现类
if (this.context instanceof ConfigurableWebApplicationContext) {
ConfigurableWebApplicationContext cwac = (ConfigurableWebApplicationContext) this.context;
//一般来说刚创建的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.
//在web.xml中配置了<context-param>的parentContextKey才会指定父级应用
ApplicationContext parent = loadParentContext(servletContext);
cwac.setParent(parent);
}
//读取相应的配置并且刷新context对象
configureAndRefreshWebApplicationContext(cwac, 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(ServletContext context)和configureAndRefreshWebApplicationContext(ConfigurableWebApplicationContext wac,ServletContext sc),本文必须对这两个方法进行相应的解读
ContextLoader#createWebApplicationContext(ServletContext context)
代码清单如下
//决定采用默认的contextClass还是ServletContext中的参数属性contextClass
Class<?> contextClass = determineContextClass(sc);
//这里Spring强调指定的contextClass必须是ConfigurableWebApplicationContext的实现类或者子类
if (!ConfigurableWebApplicationContext.class.isAssignableFrom(contextClass)) {
throw new ApplicationContextException("Custom context class [" + contextClass.getName() +
"] is not of type [" + ConfigurableWebApplicationContext.class.getName() + "]");
}
//这里就是实例化指定的contextClass
return (ConfigurableWebApplicationContext) BeanUtils.instantiateClass(contextClass);
实现的主要功能为创建ConfigurableWebApplicationContext对象,这里可以稍微瞄一眼determineContextClass(ServletContext context)
//优先从ServletContext取contextClass参数对应的值,即查看是否在web.xml中配置
//对应的contextClass<context-param>参数值
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);
}
}
else {
//倘若不存在,则加载指定的XmlWebApplicationContext类
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);
}
}
ContextLoader#configureAndRefreshWebApplicationContext()
代码清单如下
protected void configureAndRefreshWebApplicationContext(ConfigurableWebApplicationContext wac, ServletContext sc){
//一般此处为真
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
//获取servletContext中的contextId属性
String idParam = sc.getInitParameter(CONTEXT_ID_PARAM);
if (idParam != null) {
//存在则设为指定的id名
wac.setId(idParam);
}
else {
// Generate default id... 一般为org.springframework.web.context.WebApplicationContext:${contextPath}
wac.setId(ConfigurableWebApplicationContext.APPLICATION_CONTEXT_ID_PREFIX +
ObjectUtils.getDisplayString(sc.getContextPath()));
}
}
wac.setServletContext(sc);
//读取contextConfigLocation属性
String configLocationParam = sc.getInitParameter(CONFIG_LOCATION_PARAM);
if (configLocationParam != null) {
//设置指定的spring文件所在地,支持classpath前缀并多文件,以,;为分隔符
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
//获得真实对象为StandardEnvironment 其非ConfigurableWebEnvironment的实现类
ConfigurableEnvironment env = wac.getEnvironment();
if (env instanceof ConfigurableWebEnvironment) {
((ConfigurableWebEnvironment) env).initPropertySources(sc, null);
}
//查看是否有ApplicationContextInitializer<C extends ConfigurableApplicationContext>启动类,其实是web.xml需要指定globalInitializerClasses参数或者contextInitializerClasses参数,前提是指定的这些类的泛型类必须是wac的父类或者与wac类相同,否则就会有异常抛出
customizeContext(sc, wac);
//调用AbstractApplicationContext的refresh方法实现加载spring文件等操作
wac.refresh();
}
可见关键处理还是在AbstractApplicationContext#refresh()方法,前面都是refresh()方法的准备工作,包括指定contextConfigLocationSpring配置文件位置、给应用一个id倘若指定了contextId属性、如果指定了globalInitializerClasses或者contextInitializerClasses参数则调用其中的initialize()方法
记录总结
ContextLoader在web.xml配置文件中没有指定
contextClass的属性下会默认加载XmlWebApplicationContext类,如果指定了contextClass属性,Spring强调指定的contextClass必须是ConfigurableWebApplicationContext的实现类或者子类web.xml配置文件中如果没有指定
contextId属性,则WebApplicationContext的id为org.springframework.web.context.WebApplicationContext:${contextPath},其中${contextPath}是项目的上下文路径,例如localhost:8080/test/info/query路径下的contextPath为/testweb.xml配置的
contextConfigLocation属性支持多文件,以,;为分隔符,不指定默认会加载applicationContext.xml,其在后续章节剖析web.xml倘若指定globalInitializerClasses参数或者contextInitializerClasses参数,具体要求如下
* 指定的类实现ApplicationContextInitializer<C extends ConfigurableApplicationContext>接口
* 指定的这些类中的泛型类必须是contextClass(默认为XmlWebApplicationContext)的父类或者一致,否则就会有异常抛出
下节预告
Spring源码情操陶冶-AbstractApplicationContext
Spring源码情操陶冶-ContextLoader的更多相关文章
- Spring源码情操陶冶-AbstractApplicationContext
前言-阅读源码有利于陶冶情操,本文承接前文Spring源码情操陶冶-ContextLoader 约束:本文指定contextClass为默认的XmlWebApplicationContext Abst ...
- Spring源码情操陶冶-ContextLoaderListener
前言:通过实例结合源码的方式解读,其中涉及到的文件来自于博主的Github毕设项目wxServer Note: Springboot应用不在本文章讨论范围 web.xml中启用Spring 在一般的w ...
- Spring源码情操陶冶-AbstractApplicationContext#finishBeanFactoryInitialization
承接前文Spring源码情操陶冶-AbstractApplicationContext#registerListeners 约定web.xml配置的contextClass为默认值XmlWebAppl ...
- Spring源码情操陶冶-AbstractApplicationContext#registerListeners
承接前文Spring源码情操陶冶-AbstractApplicationContext#onRefresh 约定web.xml配置的contextClass为默认值XmlWebApplicationC ...
- Spring源码情操陶冶-AbstractApplicationContext#onRefresh
承接前文Spring源码情操陶冶-AbstractApplicationContext#initApplicationEventMulticaster 约定web.xml配置的contextClass ...
- Spring源码情操陶冶-AbstractApplicationContext#initApplicationEventMulticaster
承接前文Spring源码情操陶冶-AbstractApplicationContext#initMessageSource 约定web.xml配置的contextClass为默认值XmlWebAppl ...
- Spring源码情操陶冶-AbstractApplicationContext#initMessageSource
承接前文Spring源码情操陶冶-AbstractApplicationContext#registerBeanPostProcessors 约定web.xml配置的contextClass为默认值X ...
- Spring源码情操陶冶-AbstractApplicationContext#registerBeanPostProcessors
承接前文Spring源码情操陶冶-AbstractApplicationContext#invokeBeanFactoryPostProcessors 瞧瞧官方注释 /** * Instantiate ...
- Spring源码情操陶冶-AbstractApplicationContext#invokeBeanFactoryPostProcessors
阅读源码有利于陶冶情操,承接前文Spring源码情操陶冶-AbstractApplicationContext#postProcessBeanFactory 约定:web.xml中配置的context ...
随机推荐
- bettercap实现内网Dns欺骗
目的 让内网的所有计算机浏览网页的时候, 出现我的钓鱼页面 准备 kali系统 Bettercap dns文件 通过ifconfig查看当前计算机的ip, 我这边为, 192.168.1.150 创建 ...
- Bash提示符
Bash有四种提示符 1.基本提示符(PS1):即$符号,是默认的基本提示符,当Shell运行在交互模式下时,该提示符会出现在屏幕上,可以设置为其它符号. 显示PS1设置[cb@cb:16:36:23 ...
- 浅谈Cordova框架的一些理解
前言 因为工作原因,最近需要研究Cordova框架,看了其中的源码和实现方式,当场在看的时候马上能理解,但是事后再回去看相关源码时候却发现之前理解的内容又忘记了,又不得不重新开始看,所以总觉得需要记录 ...
- .net core web api + Autofac + EFCore 个人实践
1.背景 去年时候,写过一篇<Vue2.0 + Element-UI + WebAPI实践:简易个人记账系统>,采用Asp.net Web API + Element-UI.当时主要是为了 ...
- scanner--inputstreamreader--console对比
1 JDK 1.4 及以下版本读取的方法 JDK 1.4 及以下的版本中要想从控制台中输入数据只有一种办法,即使用System.in获得系统的输入流,再桥接至字符流从字符流中读入数据.示例代码如下: ...
- Chapter 4. The MPEG-4 and H.264 Standards
本章节介绍一些关于MPEG-4标准与H.264标准的基本知识 比较重要的是第95页关于两种标准的对比表格.其他部分没有什么特别重要的细节.
- 【Android Developers Training】 49. 轻松录制视频
注:本文翻译自Google官方的Android Developers Training文档,译者技术一般,由于喜爱安卓而产生了翻译的念头,纯属个人兴趣爱好. 原文链接:http://developer ...
- Android如何实现定位获取
一:GPS定位: (1).要实用Adnroid平台的GPS设备,首先需要添加上权限,所以需要添加如下权限: uses-permission android:name= android.permissi ...
- C++学习笔记——大杂烩
C++学习笔记--大杂烩 by方阳 版权声明:本文为博主原创文章,转载请指明转载地址 h ...
- FFT/NTT 多项式学习笔记
FFT(快速傅立叶变换)和NTT(快速数论变换)看上去很高端,真正搞懂了就很simple了辣. 首先给出多项式的一些定义(初中数学内容): 形如Σaixi的式子就是多项式! 多项式中每个单项式叫做多项 ...