5、整合關鍵-在web.xml中配置監聽器來控制ioc容器生命周期 原因:
1、配置的組件太多,需保障單實例
2、項目停止后,ioc容器也需要關掉,降低對內存資源的占用。 項目啟動創建容器,項目停止銷毀容器。
利用ServletContextListener監控項目來控制。 Spring提供了了這樣的監控器:
在web.xml配置監聽器:
<!-- 監聽項目的創建和銷毀,依據此來創建和銷毀ioc容器 --> <!-- needed for ContextLoaderListener --> <context-param> <!-- 指定Spring配置文件位置 --> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </context-param> <!-- Bootstraps the root web application context before servlet initialization --> <!--項目啟動按照配置文件指定的位置創建容器,項目卸載,銷毀容器 --> <listener> <!-- 加載jar包:org.springframework.web --> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener>
打開
ContextLoaderListener源碼發現其實現了ServletContextListener,其中有兩個方法,一個創建容器,一個銷毀容器
public class ContextLoaderListener extends ContextLoader implements ServletContextListener { //... /** * Initialize the root web application context. */ @Override public void contextInitialized(ServletContextEvent event) { initWebApplicationContext(event.getServletContext()); } /** * Close the root web application context. */ @Override public void contextDestroyed(ServletContextEvent event) { closeWebApplicationContext(event.getServletContext()); ContextCleanupListener.cleanupAttributes(event.getServletContext()); } }
ContextLoader
初始化WebApplicationContext
由下面的核心代碼可知,創建容器后得到一個context對象 public WebApplicationContext initWebApplicationContext(ServletContext servletContext) { //創建容器 if (this.context == null) {
//private WebApplicationContext context;就是我們的ioc容器
this.context = createWebApplicationContext(servletContext); } }
context;就是我們的ioc容器,context有很多方法,
由上圖可知getCurrentWebApplicationContext()方法可以獲取當前的ioc容器。
public static WebApplicationContext getCurrentWebApplicationContext() {
ClassLoader ccl = Thread.currentThread().getContextClassLoader();
if (ccl != null) {
WebApplicationContext ccpt = currentContextPerThread.get(ccl);
if (ccpt != null) {
return ccpt;
}
}
return currentContext;
}
getCurrentWebApplicationContext()屬於ContextLoader類的,因為屬於static,所以監聽器來控制ioc容器生命周期
代碼如下:
private static ApplicationContext ioc = ContextLoader.getCurrentWebApplicationContext();