上一篇關(guān)于Spring是如何啟動(dòng)的文章,主要是分析了從Tomcat啟動(dòng)到web.xml文件加載,再到通過(guò)ContextLoaderListener
監(jiān)聽(tīng)器開(kāi)始初始化WebApplicationContext
這個(gè)過(guò)程,如果不熟悉可以參考這篇-漫談Spring的啟動(dòng)與初始化(一),但是上一篇還沒(méi)有分析到Spring容器是如何通過(guò)web.xml里面配置的contextConfigLocation
參數(shù)和Spring容器的配置文件applicationContext.xml
來(lái)初始化Spring,本文著力于解決這個(gè)疑惑。
initWebApplicationContext方法
當(dāng)ContextLoaderListener
監(jiān)聽(tīng)到ServletContext
初始化事件的時(shí)候就會(huì)調(diào)用ContextLoader
的initWebApplicationContext
方法,這個(gè)方法完成了很多的工作,其中便有下面這段關(guān)鍵代碼,源碼如下:
private WebApplicationContext context;
public WebApplicationContext initWebApplicationContext(ServletContext servletContext) {
...
if(this.context == null) {
//如果context為null就開(kāi)始創(chuàng)建WebApplicationContext
this.context = this.createWebApplicationContext(servletContext);
}
...
}
createWebApplicationContext方法
下面進(jìn)入該方法,源碼如下:
protected WebApplicationContext createWebApplicationContext(ServletContext sc) {
Class contextClass = this.determineContextClass(sc);
if(!ConfigurableWebApplicationContext.class.isAssignableFrom(contextClass)) {
throw new ApplicationContextException("Custom context class [" + contextClass.getName() + "] is not of type [" + ConfigurableWebApplicationContext.class.getName() + "]");
} else {
//根據(jù)類(lèi)返回實(shí)例
return (ConfigurableWebApplicationContext)BeanUtils.instantiateClass(contextClass);
}
}
其中determineContextClass(sc)
方法是用來(lái)尋找實(shí)現(xiàn)WebApplicationContext
接口的類(lèi),實(shí)現(xiàn)方法如下:
protected Class<?> determineContextClass(ServletContext servletContext) {
//關(guān)鍵代碼一:
String contextClassName = servletContext.getInitParameter("contextClass");
if(contextClassName != null) {
try {
return ClassUtils.forName(contextClassName, ClassUtils.getDefaultClassLoader());
} catch (ClassNotFoundException var4) {
throw new ApplicationContextException("Failed to load custom context class [" + contextClassName + "]", var4);
}
} else {
//關(guān)鍵代碼二:
contextClassName = defaultStrategies.getProperty(WebApplicationContext.class.getName());
try {
return ClassUtils.forName(contextClassName, ContextLoader.class.getClassLoader());
} catch (ClassNotFoundException var5) {
throw new ApplicationContextException("Failed to load default context class [" + contextClassName + "]", var5);
}
}
}
上面這兩行代碼就是決定返回的Class:如果開(kāi)發(fā)人員在web.xml中配置了一個(gè)參數(shù)名為contextClass
,值為WebApplicationContext
接口實(shí)現(xiàn)類(lèi),那getInitParameter("contextClass")
就會(huì)返回這個(gè)配置的實(shí)現(xiàn)類(lèi)Class;如果沒(méi)有配置,也就是contextClassName==null
,那么通過(guò)defaultStrategies.getProperty(...)
則會(huì)返回Spring默認(rèn)的實(shí)現(xiàn)類(lèi)XmlWebApplicationContext
??赡苡型瑢W(xué)會(huì)好奇為什么是這個(gè),這個(gè)類(lèi)是從哪兒來(lái)的。
我們回頭在ContextLoader
這個(gè)類(lèi)中最下面可以看到有這么幾行靜態(tài)代碼段,在類(lèi)一加載的時(shí)候執(zhí)行,如下:
public class ContextLoader {
private static final Properties defaultStrategies;
static {
try {
ClassPathResource ex = new ClassPathResource("ContextLoader.properties", ContextLoader.class);
defaultStrategies = PropertiesLoaderUtils.loadProperties(ex);
} catch (IOException var1) {
throw new IllegalStateException("Could not load \'ContextLoader.properties\': " + var1.getMessage());
}
currentContextPerThread = new ConcurrentHashMap(1);
}
}
在ContextLoader.class
的同一個(gè)包下面,可以找到這個(gè)配置文件,其中只有一行配置如下:
org.springframework.web.context.WebApplicationContext=org.springframework.web.context.support.XmlWebApplicationContext
XmlWebApplicationContext
這個(gè)類(lèi)就是WebApplicationContext
這個(gè)接口最終的實(shí)現(xiàn)類(lèi),也是Spring啟動(dòng)時(shí)默認(rèn)使用的類(lèi)。其實(shí)還有一些實(shí)現(xiàn)類(lèi),讓我們自己去加載applicationContext.xml
,比如ClassPathXmlApplicationContext
。
這樣在上述的createWebApplicationContext
方法中,我們拿到的就是XmlWebApplicationContext.class
,然后通過(guò)BeanUtils.instantiateClass(contextClass)
方法根據(jù)類(lèi)名創(chuàng)建對(duì)應(yīng)實(shí)例,并且進(jìn)行強(qiáng)制轉(zhuǎn)換得到ConfigurableWebApplicationContext
接口的實(shí)例,因?yàn)?code>XmlWebApplicationContext是后者的實(shí)現(xiàn)類(lèi),所以這樣轉(zhuǎn)換是沒(méi)問(wèn)題的(當(dāng)然沒(méi)問(wèn)題哈哈)。
那么createWebApplicationContext
方法分析到此為止。
我們繼續(xù)看initWebApplicationContext
方法中下面這段代碼的最后一行:
if(this.context == null) {
//如果context為null就開(kāi)始創(chuàng)建WebApplicationContext
this.context = this.createWebApplicationContext(servletContext);
}
if(this.context instanceof ConfigurableWebApplicationContext) {
ConfigurableWebApplicationContext err = (ConfigurableWebApplicationContext)this.context;
if(!err.isActive()) {
...
//關(guān)鍵代碼:配置和刷新WebApplicationContext,這里其實(shí)就是XmlWebApplicationContext了
this.configureAndRefreshWebApplicationContext(err, servletContext);
}
}
configureAndRefreshWebApplicationContext方法
在上面代碼中我們通過(guò)XmlWebApplicationContext
類(lèi)創(chuàng)建了WebApplicationContext
的實(shí)例,本節(jié)方法則是為該實(shí)例設(shè)置一些配置信息和創(chuàng)建各種bean。我們重點(diǎn)關(guān)注下面幾行代碼:
protected void configureAndRefreshWebApplicationContext(ConfigurableWebApplicationContext wac, ServletContext sc) {
...
wac.setServletContext(sc);
//關(guān)鍵代碼一:在ServletContext中獲取contextConfigLocation值,查找配置文件地址
configLocationParam = sc.getInitParameter("contextConfigLocation");
if(configLocationParam != null) {
wac.setConfigLocation(configLocationParam);
}
...
//關(guān)鍵代碼二:刷新XmlWebApplicationContext
wac.refresh();
}
在Spring的項(xiàng)目中,經(jīng)常要在web.xml中配置contextConfigLocation的參數(shù),我們對(duì)于下面的幾行xml代碼應(yīng)該也很熟悉,它設(shè)置了Spring容器配置文件的路徑:
<!-- Context ConfigLocation -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:/spring-context*.xml</param-value>
</context-param>
既然是在web.xml中配置的這些參數(shù),為什么是在ServletContext中去取呢?在上一篇文章中分析過(guò),Tomcat在加載web.xml文件時(shí),會(huì)最終將該配置文件的配置屬性參數(shù)以鍵值對(duì)的形式存放在每個(gè)web應(yīng)用對(duì)應(yīng)的ServletContext中,這樣我們?cè)趙eb應(yīng)用中的任何地方都可以拿到該參數(shù)值(后面還會(huì)提到ServletContext其他的使用場(chǎng)景)。
當(dāng)然,如果我們沒(méi)有在web.xml中配置該參數(shù)的話(huà),XmlWebApplicationContext類(lèi)也是有默認(rèn)值的,如下:
public class XmlWebApplicationContext extends AbstractRefreshableWebApplicationContext {
public static final String DEFAULT_CONFIG_LOCATION = "/WEB-INF/applicationContext.xml";
public static final String DEFAULT_CONFIG_LOCATION_PREFIX = "/WEB-INF/";
public static final String DEFAULT_CONFIG_LOCATION_SUFFIX = ".xml";
}
到這里,配置文件信息拿到了,再就是wac.refresh()
方法了,這個(gè)方法具體實(shí)現(xiàn)在A(yíng)bstractApplicationContext類(lèi)中,進(jìn)入該方法:
public void refresh() throws BeansException, IllegalStateException {
Object var1 = this.startupShutdownMonitor;
synchronized(this.startupShutdownMonitor) {
//容器預(yù)先準(zhǔn)備,記錄容器啟動(dòng)時(shí)間和標(biāo)記
prepareRefresh();
//創(chuàng)建bean工廠(chǎng),里面實(shí)現(xiàn)了BeanDefinition的裝載
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
//配置bean工廠(chǎng)的上下文信息,如類(lèi)裝載器等
prepareBeanFactory(beanFactory);
try {
//在BeanDefinition被裝載后,提供一個(gè)修改BeanFactory的入口
postProcessBeanFactory(beanFactory);
//在bean初始化之前,提供對(duì)BeanDefinition修改入口,PropertyPlaceholderConfigurer在這里被調(diào)用
invokeBeanFactoryPostProcessors(beanFactory);
//注冊(cè)各種BeanPostProcessors,用于在bean被初始化時(shí)進(jìn)行攔截,進(jìn)行額外初始化操作
registerBeanPostProcessors(beanFactory);
//初始化MessageSource
initMessageSource();
//初始化上下文事件廣播
initApplicationEventMulticaster();
//模板方法
onRefresh();
//注冊(cè)監(jiān)聽(tīng)器
registerListeners();
//初始化所有未初始化的非懶加載的單例Bean
finishBeanFactoryInitialization(beanFactory);
//發(fā)布事件通知
finishRefresh();
} catch (BeansException var5) {
if(this.logger.isWarnEnabled()) {
this.logger.warn("Exception encountered during context initialization - cancelling refresh attempt: " + var5);
}
this.destroyBeans();
this.cancelRefresh(var5);
throw var5;
}
}
}
這個(gè)方法里面就是IOC容器初始化的大致步驟了。
after configureAndRefresh
在IOC容器初始化之后,也就是configureAndRefreshWebApplicationContext方法執(zhí)行結(jié)束后有一行代碼如下:
//關(guān)鍵代碼:
servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, this.context);
可以看到,這里初始化后的context被存放到了servletContext中,具體的就是存到了一個(gè)Map變量中,key值就是WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE這個(gè)常量。這個(gè)key常量在WebApplicationContext接口中設(shè)置的,如下:
public interface WebApplicationContext extends ApplicationContext {
//org.springframework.web.context.WebApplicationContext.ROOT
String ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE = WebApplicationContext.class.getName() + ".ROOT";
}
另外,我們也可以使用Spring的WebApplicationContextUtils工具類(lèi)獲取這個(gè)WebApplicationContext(不過(guò)這里request獲取ServletContext是有限制的,要求servlet-api.jar 包的版本是在3.0以上)方式如下:
WebApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContext(request.getServletContext());
到這里Spring的啟動(dòng)與初始化應(yīng)該就結(jié)束了,這里面要理清ServletContext和Spring容器的關(guān)系,整個(gè)Spring容器被放置在ServletContext這樣一個(gè)類(lèi)似于Map的結(jié)構(gòu)中。ServletContext 從字面上理解也是Servlet的容器,被 Servlet 程序間接用來(lái)與外層 Web 容器通信,例如寫(xiě)日志,轉(zhuǎn)發(fā)請(qǐng)求等。每一個(gè) Web 應(yīng)用程序含有一個(gè)Context ,被Web 應(yīng)用內(nèi)的各個(gè)程序共享。因?yàn)镃ontext 可以用來(lái)保存資源并且共享,所以ServletContext 的常用場(chǎng)景是Web級(jí)應(yīng)用緩存---- 把不經(jīng)常更改的內(nèi)容讀入內(nèi)存,所以服務(wù)器響應(yīng)請(qǐng)求的時(shí)候就不需要進(jìn)行慢速的磁盤(pán)I/O 了。
參考
深入理解Spring系列之七:web應(yīng)用自動(dòng)裝配Spring配置
-EOF-