Spring分別提供了用於啓動WebApplicationContext的Servlet和Web容器監聽器:
org.springframework.web.context.ContextLoaderServlet;
org.springframework.web.context.ContextLoaderListener.
這兩個方法都是在web應用啓動的時候來初始化WebApplicationContext,我個人認爲Listerner要比Servlet更好一些,因爲Listerner監聽應用的啓動和結束,而Servlet得啓動要稍微延遲一些,如果在這時要做一些業務的操作,啓動的前後順序是有影響的。
配置例子如下:
context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
以ContextLoaderListener爲例,我們可以看到
public void contextInitialized(ServletContextEvent event) {
this.contextLoader = createContextLoader();
this.contextLoader.initWebApplicationContext(event.getServletContext());
}
protected ContextLoader createContextLoader() {
return new ContextLoader();
}
ContextLoader是一個工具類,用來初始化WebApplicationContext,其主要方法就是initWebApplicationContext,我們繼續追蹤initWebApplicationContext這個方法(具體代碼我不貼出,大家可以看Spring中的源碼),我們發現,原來ContextLoader是把WebApplicationContext(XmlWebApplicationContext是默認實現類)放在了ServletContext中,ServletContext也是一個“容器”,也是一個類似Map的結構,而WebApplicationContext在ServletContext中的KEY就是WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE,我們如果要使用WebApplicationContext則需要從ServletContext取出,Spring提供了一個WebApplicationContextUtils類,可以方便的取出WebApplicationContext,只要把ServletContext傳入就可以了。