1. 程式人生 > >Spring IOC 容器的啟動與銷燬

Spring IOC 容器的啟動與銷燬

AbstractApplicationContext 是一個抽象類,IOC 容器的啟動和銷燬分別始於它的 refresh 和 doClose 方法。

Web 專案中,web.xml 中配置如下:

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/applicationContext.xml,/WEB-INF/action-servlet.xml</param-value>
</context-param>
<listener>
    <listener-class> 
        org.springframework.web.context.ContextLoaderListener
    </listener-class>
</listener>

ContextLoaderListener 用來監聽 ServletContext 的生命週期,由於 ServletContext 代表應用本身,因此可以說 Web 應用的啟動和銷燬,分別觸發了 Spring IOC 容器的啟動和銷燬。

public class ContextLoaderListener extends ContextLoader implements ServletContextListener {

    //初始化 web 容器
    @Override
    public void contextInitialized(ServletContextEvent event) {
        //初始化 IOC 容器
        initWebApplicationContext(event.getServletContext());
    }

    //關閉 web 容器
    @Override
    public void contextDestroyed(ServletContextEvent event) {
        //關閉 IOC 容器
        closeWebApplicationContext(event.getServletContext());
        ContextCleanupListener.cleanupAttributes(event.getServletContext());
    }

}

initWebApplicationContext 方法做了以下幾件事:

  1. 建立 WebApplicationContext 物件,這個物件的型別預設為 XmlWebApplicationContext(來自於ContextLoader.properties)。
  2. 設定配置檔案的位置 wac.setConfigLocation(configLocationParam),這個配置從 web.xml 中讀取。
  3. 執行 AbstractApplicationContext 的 refresh 方法,啟動 IOC 容器。

closeWebApplicationContext 方法,會執行 AbstractApplicationContext 的 doClose 方法。