SpringMVC源碼閱讀:ContextLoaderListener初始化過程

概述

  • Tomcat或Jetty作爲Servlet容器會爲每一個Web應用構建一個ServletContext用於存放所有的Servlet, Filter, Listener。
  • ContextLoaderListener 作爲一個Listener會首先啓動,創建一個WebApplicationContext用於加載除Controller等Web組件以外的所有bean,這個ApplicationContext作爲根容器存在,對於整個Web應用來說,只能存在一個,也就是父容器,會被所有子容器共享,子容器可以訪問父容器裏的bean,反過來則不行。

web.xml配置

ContextLoaderListener監聽器的作用就是啓動web容器時,自動裝配ApplicationContext的配置信息。它實現了ServletContextListener接口,在web.xml文件中配置這個監聽器,Tomcat或Jetty啓動容器時,就會默認執行它實現的方法。

<!-- 配置spring IOC參數路徑 -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath*:/spring-context*.xml</param-value>
    </context-param> 
<!-- Spring監聽器 -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-    
         class>
    </listener>

通過擴展ContextLoaderListener類,可以增加初始化時的個性化功能,如輸出產品的信息等。

獲取WebApplicationContext的實現類

在org.springframework.web.context.ContextLoader中有一個靜態屬性,

static {
        // Load default strategy implementations from properties file.
        // This is currently strictly internal and not meant to be customized
        // by application developers.
        try {
            ClassPathResource resource = new ClassPathResource(DEFAULT_STRATEGIES_PATH, ContextLoader.class);
            defaultStrategies = PropertiesLoaderUtils.loadProperties(resource);
        }
        catch (IOException ex) {
            throw new IllegalStateException("Could not load 'ContextLoader.properties': " + ex.getMessage());
        }
    }

默認的DEFAULT_STRATEGIES_PATH=ContextLoader.properties,路徑在ContextLoader類的同一級目錄下,都在spring-web-..*.RELEASE.jar包內。ContextLoader.properties的內容爲:

# Default WebApplicationContext implementation class for ContextLoader.
# Used as fallback when no explicit context implementation has been specified as context-param.
# Not meant to be customized by application developers.

org.springframework.web.context.WebApplicationContext=org.springframework.web.context.support.XmlWebApplicationContext

實際的實例化爲org.springframework.web.context.support.XmlWebApplicationContext。

知識點

  • org.springframework.core.ioClassPathResource和PropertiesLoaderUtils.loadProperties()組合讀取jar包中的properties配置文件。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章