一、web.xml 中經常有如下配置
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
contextConfigLocation 參數指定了spring啓動要加載的配置文件,如果不指定,Spring 會加載WEB-INF目錄下applicationContext.xml
二、ContextLoaderListener分析
ContextLoaderListener類圖
可以看到
- ContextLoaderListener實現了ServletContextListener接口,繼承了ContextLoader類。
- ServletContextListener用於監聽ServletContext的創建和銷燬,而ServletContext隨着服務器啓動而創建,隨着服務器關閉而銷燬。
- ContextLoaderListener實現了ServletContextListener的接口方法:contextInitialized和contextDestroyed 方法分別調用了 ContextLoader裏面的initWebApplicationContext和closeWebApplicationContext方法
- initWebApplicationContext的過程可以描述爲:先判斷WebApplicationContext是否已存在,不存在的話則初始化一個XmlWebApplicationContext(WebApplicationContext的子類),並把該實例put到 currentContextPerThread 中。因此可以通過ContextLoader獲取WebApplicationContext。
- 根據下面代碼片段知道contextParam中的contextConfigLocation這個參數名是根據這裏來寫的
public static final String CONFIG_LOCATION_PARAM = "contextConfigLocation";
...
String configLocationParam = sc.getInitParameter(CONFIG_LOCATION_PARAM);
if (configLocationParam != null) {
wac.setConfigLocation(configLocationParam);
}