ContextLoaderListener的源碼分析
本篇是截取我的這篇文章:ServletContext,WebApplicationContext、Servlet初始化
首先,我們從web.xml中開始,在web.xml中我們首先配置的是contextLoaderListener,它的作用就是啓動web容器時,自動裝配ApplicationContext的配置信息。因爲它實現了ServletContextListener這個接口,在web.xml配置這個監聽器,啓動容器時,就會自動執行它實現的contextInitialized()方法。這樣就能夠在客戶端請求之前向ServletContext中添加任意的對象。
在ServletContextListener中的核心邏輯便是初始化WebApplicationContext實例並存放至ServletContext中。
public void contextInitialized(ServletContextEvent event) {
this.contextLoader = createContextLoader();
if (this.contextLoader == null) {
this.contextLoader = this;
}
this.contextLoader.initWebApplicationContext(event.getServletContext());
}
通過源碼可以看出contextInitialized()中創建了一個contextLoader對象,然後該對象調用了initWebApplicationContext()。
public WebApplicationContext initWebApplicationContext(ServletContext servletContext) {
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) {
//注意這裏:創建實例
this.context = createWebApplicationContext(servletContext);
}
if (this.context instanceof ConfigurableWebApplicationContext) {
configureAndRefreshWebApplicationContext((ConfigurableWebApplicationContext)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;
}
}
initWebApplicationContext()主要是WebApplicationContext創建的過程:首先,驗證WebApplicationContext的存在性,通過查看ServletContext實例中是否有對應key的屬性驗證WebApplicationContext是否已經創建過實例。如果沒有通過**createWebApplicationContext()**方法來創建實例,並存放至ServletContext中。
protected WebApplicationContext createWebApplicationContext(ServletContext sc) {
//
Class<?> contextClass = determineContextClass(sc);
if (!ConfigurableWebApplicationContext.class.isAssignableFrom(contextClass)) {
throw new ApplicationContextException("Custom context class [" + contextClass.getName() +
"] is not of type [" + ConfigurableWebApplicationContext.class.getName() + "]");
}
ConfigurableWebApplicationContext wac =
(ConfigurableWebApplicationContext) BeanUtils.instantiateClass(contextClass);
return wac;
}
從源碼中可以詳細的看到return wac,是通過BeanUtils.instantiateClass()來創建實例,但是其中傳遞了一個contextClass,該對象是通過determineContextClass方法創建的,接下來分析該方法的源碼:
protected Class<?> determineContextClass(ServletContext servletContext) {
//首先從servletContext對象中獲取值
String contextClassName = servletContext.getInitParameter(CONTEXT_CLASS_PARAM);
if (contextClassName != null) {
try {
//該值不爲null通過forName()來裝載該類
return ClassUtils.forName(contextClassName, ClassUtils.getDefaultClassLoader());
}
catch (ClassNotFoundException ex) {
throw new ApplicationContextException(
"Failed to load custom context class [" + contextClassName + "]", ex);
}
}
else {
//servletContext中沒有該對象時
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);
}
}
}
該方法很詳細的解釋了是如何獲取CONTEXT_CLASS_PARAM(類名參數)。
首先如果contextClassName不爲空時就通過forName來裝載這個類,很明顯第一次啓動web容器時contextClassName爲空。
當contextClassName爲空時通過defaultStrategies.getProperty()獲得實現類的名稱,而defaultStrategies是在ContextLoader類的靜態代碼塊中賦值的。具體的途徑,則是讀取ContextLoader類的同目錄下的ContextLoader.properties屬性文件來確定的。
org.springframework.web.context.WebApplicationContext=org.springframework.web.context.support.XmlWebApplicationContext
找到該文件後發現裏面存儲了一個鍵值對,故會加載這個類org.springframework.web.context.support.XmlWebApplicationContext
也就是說,在初始化的過程中,程序會首先讀取ContextLoader類的同目錄下的屬性文件ContextLoader.properties,並根據其中的配置提取將要實現WebApplicationContext接口的實現類,並根據這個類通過反射進行實例的創建。
綜合以上的代碼:ContextLoaderListener監聽器的作用就是啓動Web容器時,自動裝配ApplicationContext的配置信息。因爲它實現了ServletContextListener這個接口,在web.xml配置了這個監聽器,啓動容器時,就會默認執行它實現的contextInitialized()方法初始化WebApplicationContext實例(XmlWebApplicationContext),並放入到ServletContext中。由於在ContextLoaderListener中關聯了ContextLoader這個類,所以整個加載配置過程由ContextLoader來完成。