上一篇關(guān)于Spring是如何啟動(dòng)的文章鸭栖,主要是分析了從Tomcat啟動(dòng)到web.xml文件加載,再到通過ContextLoaderListener
監(jiān)聽器開始初始化WebApplicationContext
這個(gè)過程误墓,如果不熟悉可以參考這篇-漫談Spring的啟動(dòng)與初始化(一),但是上一篇還沒有分析到Spring容器是如何通過web.xml里面配置的contextConfigLocation
參數(shù)和Spring容器的配置文件applicationContext.xml
來初始化Spring户魏,本文著力于解決這個(gè)疑惑饮戳。
initWebApplicationContext方法
當(dāng)ContextLoaderListener
監(jiān)聽到ServletContext
初始化事件的時(shí)候就會(huì)調(diào)用ContextLoader
的initWebApplicationContext
方法闲孤,這個(gè)方法完成了很多的工作谆级,其中便有下面這段關(guān)鍵代碼,源碼如下:
private WebApplicationContext context;
public WebApplicationContext initWebApplicationContext(ServletContext servletContext) {
...
if(this.context == null) {
//如果context為null就開始創(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ù)類返回實(shí)例
return (ConfigurableWebApplicationContext)BeanUtils.instantiateClass(contextClass);
}
}
其中determineContextClass(sc)
方法是用來尋找實(shí)現(xiàn)WebApplicationContext
接口的類哨苛,實(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:如果開發(fā)人員在web.xml中配置了一個(gè)參數(shù)名為contextClass
,值為WebApplicationContext
接口實(shí)現(xiàn)類币砂,那getInitParameter("contextClass")
就會(huì)返回這個(gè)配置的實(shí)現(xiàn)類Class建峭;如果沒有配置,也就是contextClassName==null
决摧,那么通過defaultStrategies.getProperty(...)
則會(huì)返回Spring默認(rèn)的實(shí)現(xiàn)類XmlWebApplicationContext
亿蒸。可能有同學(xué)會(huì)好奇為什么是這個(gè)掌桩,這個(gè)類是從哪兒來的边锁。
我們回頭在ContextLoader
這個(gè)類中最下面可以看到有這么幾行靜態(tà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è)類就是WebApplicationContext
這個(gè)接口最終的實(shí)現(xiàn)類则拷,也是Spring啟動(dòng)時(shí)默認(rèn)使用的類贡蓖。其實(shí)還有一些實(shí)現(xiàn)類,讓我們自己去加載applicationContext.xml
煌茬,比如ClassPathXmlApplicationContext
斥铺。
這樣在上述的createWebApplicationContext
方法中,我們拿到的就是XmlWebApplicationContext.class
坛善,然后通過BeanUtils.instantiateClass(contextClass)
方法根據(jù)類名創(chuàng)建對應(yīng)實(shí)例晾蜘,并且進(jìn)行強(qiáng)制轉(zhuǎn)換得到ConfigurableWebApplicationContext
接口的實(shí)例,因?yàn)?code>XmlWebApplicationContext是后者的實(shí)現(xiàn)類眠屎,所以這樣轉(zhuǎn)換是沒問題的(當(dāng)然沒問題哈哈)剔交。
那么createWebApplicationContext
方法分析到此為止。
我們繼續(xù)看initWebApplicationContext
方法中下面這段代碼的最后一行:
if(this.context == null) {
//如果context為null就開始創(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方法
在上面代碼中我們通過XmlWebApplicationContext
類創(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ù),我們對于下面的幾行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中去取呢?在上一篇文章中分析過蛉鹿,Tomcat在加載web.xml文件時(shí)滨砍,會(huì)最終將該配置文件的配置屬性參數(shù)以鍵值對的形式存放在每個(gè)web應(yīng)用對應(yīng)的ServletContext中,這樣我們在web應(yīng)用中的任何地方都可以拿到該參數(shù)值(后面還會(huì)提到ServletContext其他的使用場景)妖异。
當(dāng)然惋戏,如果我們沒有在web.xml中配置該參數(shù)的話,XmlWebApplicationContext類也是有默認(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)在AbstractApplicationContext類中舔亭,進(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工廠蟀俊,里面實(shí)現(xiàn)了BeanDefinition的裝載
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
//配置bean工廠的上下文信息钦铺,如類裝載器等
prepareBeanFactory(beanFactory);
try {
//在BeanDefinition被裝載后,提供一個(gè)修改BeanFactory的入口
postProcessBeanFactory(beanFactory);
//在bean初始化之前肢预,提供對BeanDefinition修改入口矛洞,PropertyPlaceholderConfigurer在這里被調(diào)用
invokeBeanFactoryPostProcessors(beanFactory);
//注冊各種BeanPostProcessors,用于在bean被初始化時(shí)進(jìn)行攔截烫映,進(jìn)行額外初始化操作
registerBeanPostProcessors(beanFactory);
//初始化MessageSource
initMessageSource();
//初始化上下文事件廣播
initApplicationEventMulticaster();
//模板方法
onRefresh();
//注冊監(jiān)聽器
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工具類獲取這個(gè)WebApplicationContext(不過這里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è)類似于Map的結(jié)構(gòu)中较幌。ServletContext 從字面上理解也是Servlet的容器揍瑟,被 Servlet 程序間接用來與外層 Web 容器通信,例如寫日志乍炉,轉(zhuǎn)發(fā)請求等绢片。每一個(gè) Web 應(yīng)用程序含有一個(gè)Context 滤馍,被Web 應(yīng)用內(nèi)的各個(gè)程序共享。因?yàn)镃ontext 可以用來保存資源并且共享底循,所以ServletContext 的常用場景是Web級應(yīng)用緩存---- 把不經(jīng)常更改的內(nèi)容讀入內(nèi)存巢株,所以服務(wù)器響應(yīng)請求的時(shí)候就不需要進(jìn)行慢速的磁盤I/O 了。
參考
深入理解Spring系列之七:web應(yīng)用自動(dòng)裝配Spring配置
-EOF-