1. 程式人生 > >spring 啟動過程原始碼解析

spring 啟動過程原始碼解析

開發十年,就只剩下這套架構體系了! >>>   

Spring web啟動流程原始碼分析:

當一個Web應用部署到容器內時(eg.tomcat),在Web應用開始響應執行使用者請求前,以下步驟會被依次執行:

  • 部署描述檔案中(eg.tomcat的web.xml)由<listener>元素標記的事件監聽器會被建立和初始化
  • 對於所有事件監聽器,如果實現了ServletContextListener介面,將會執行其實現的contextInitialized()方法
  • 部署描述檔案中由<filter>元素標記的過濾器會被建立和初始化,並呼叫其init()方法
  • 部署描述檔案中由<servlet>元素標記的servlet會根據<load-on-startup>的權值按順序建立和初始化,並呼叫其init()方法

通過上述官方文件的描述,可繪製如下Web應用部署初始化流程執行圖。

tomcat web容器啟動時載入web.xml檔案,相關元件啟動順序為: 解析<context-param> => 解析<listener> => 解析<filter> => 解析

<servlet>,具體初始化過程如下:

  • 1、解析<context-param>裡的鍵值對。
  • 2、建立一個application內建物件即ServletContext,servlet上下文,用於全域性共享。
  • 3、將<context-param>的鍵值對放入ServletContextapplication中,Web應用內全域性共享。
  • 4、讀取<listener>標籤建立監聽器,一般會使用ContextLoaderListener類,如果使用了ContextLoaderListener類,Spring就會建立一個WebApplicationContext
    類的物件,WebApplicationContext類就是IoC容器ContextLoaderListener類建立的IoC容器IoC容器為全域性性的,並將其放置在appication中,作為應用內全域性共享,鍵名為WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE,可以通過以下兩種方法獲取

WebApplicationContext applicationContext = (WebApplicationContext) application.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);

 

WebApplicationContext applicationContext1 = WebApplicationContextUtils.getWebApplicationContext(application);

這個全域性的IoC容器只能獲取到在該容器中建立的Bean不能訪問到其他容器建立的Bean,也就是讀取web.xml配置的contextConfigLocation引數的xml檔案來建立對應的Bean

  • 5、listener建立完成後如果有<filter>則會去建立filter
  • 6、初始化建立<servlet>,一般使用DispatchServlet類。
  • 7、DispatchServlet的父類FrameworkServlet會重寫其父類的initServletBean方法,並呼叫initWebApplicationContext()以及onRefresh()方法。
  • 8、initWebApplicationContext()方法會建立一個當前servlet的一個IoC子容器,如果存在上述的全域性WebApplicationContext則將其設定為父容器,如果不存在上述全域性的則父容器為null。
  • 9、讀取<servlet>標籤的<init-param>配置的xml檔案並載入相關Bean
  • 10、onRefresh()方法建立Web應用相關元件。

web.xml

<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">
    <display-name>spring</display-name>
    <!--spring容器初始化配置-->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath*:beans.xml</param-value>
    </context-param>

    <!--spring容器初始化監聽器-->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <filter>
        <filter-name>characterEncodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
        <init-param>
            <param-name>forceEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>characterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:dispatcher-servlet.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>


</web-app>

啟動過程分析:

1. Listener的初始化過程

<context-param>標籤的內容讀取後會被放進application中,做為Web應用的全域性變數使用,接下來建立listener時會使用到這個全域性變數,因此,Web應用在容器中部署後,進行初始化時會先讀取這個全域性變數,之後再進行上述講解的初始化啟動過程。

接著定義了一個ContextLoaderListener類的listener。檢視ContextLoaderListener的類宣告原始碼如下圖:

public class ContextLoaderListener extends ContextLoader implements ServletContextListener {
…
/**
 * Initialize the root web application context.
 */
@Override
public void contextInitialized(ServletContextEvent event) {
   initWebApplicationContext(event.getServletContext());
}
…
}

ContextLoaderListener類繼承了ContextLoader類並實現了ServletContextListener介面,

首先看一下前面講述的ServletContextListener介面原始碼:

/** 
    * Implementations of this interface receive notifications about
    * changes to the servlet context of the web application they are
    * part of.
    * To receive notification events, the implementation class
    * must be configured in the deployment descriptor for the web
    * application.
    * @see ServletContextEvent
    * @since  v 2.3
    */

public interface ServletContextListener extends EventListener {
   /**
    ** Notification that the web application initialization
    ** process is starting.
    ** All ServletContextListeners are notified of context
    ** initialization before any filter or servlet in the web
    ** application is initialized.
    */

    public void contextInitialized ( ServletContextEvent sce );

   /**
    ** Notification that the servlet context is about to be shut down.
    ** All servlets and filters have been destroy()ed before any
    ** ServletContextListeners are notified of context
    ** destruction.
    */
    public void contextDestroyed ( ServletContextEvent sce );
}

該介面只有兩個方法contextInitializedcontextDestroyed,這裡採用的是觀察者模式,也稱為訂閱-釋出模式,實現了該介面的listener會向釋出者進行訂閱,當Web應用初始化或銷燬時會分別呼叫上述兩個方法。

 

繼續看ContextLoaderListener,該listener實現了ServletContextListener介面,因此在Web應用初始化時會呼叫該方法,該方法的具體實現如下:

/**
 * Initialize the root web application context.
 */
@Override
public void contextInitialized(ServletContextEvent event) {
   initWebApplicationContext(event.getServletContext());
}

ContextLoaderListenercontextInitialized()方法直接呼叫了initWebApplicationContext()方法,這個方法是繼承自ContextLoader類,通過函式名可以知道,該方法是用於初始化Web應用上下文,即IoC容器,這裡使用的是代理模式,繼續檢視ContextLoader類的initWebApplicationContext()方法的原始碼如下:

/**
 * Initialize Spring's web application context for the given servlet context,
 * using the application context provided at construction time, or creating a new one
 * according to the "{@link #CONTEXT_CLASS_PARAM contextClass}" and
 * "{@link #CONFIG_LOCATION_PARAM contextConfigLocation}" context-params.
 * @param servletContext current servlet context
 * @return the new WebApplicationContext
 * @see #ContextLoader(WebApplicationContext)
 * @see #CONTEXT_CLASS_PARAM
 * @see #CONFIG_LOCATION_PARAM
 */
public WebApplicationContext initWebApplicationContext(ServletContext servletContext) {
/*
首先通過WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE
這個String型別的靜態變數獲取一個根IoC容器,根IoC容器作為全域性變數
儲存在application物件中,如果存在則有且只能有一個
如果在初始化根WebApplicationContext即根IoC容器時發現已經存在
則直接丟擲異常,因此web.xml中只允許存在一個ContextLoader類或其子類的物件
*/

   if (servletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE) != null) {
      throw new IllegalStateException(
            "Cannot initialize context because there is already a root application context present - " +
            "check whether you have multiple ContextLoader* definitions in your web.xml!");
   }

   Log logger = LogFactory.getLog(ContextLoader.class);
   servletContext.log("Initializing Spring root WebApplicationContext");
   if (logger.isInfoEnabled()) {
      logger.info("Root WebApplicationContext: initialization started");
   }
   long startTime = System.currentTimeMillis();

   try {
      // Store context in local instance variable, to guarantee that
      // it is available on ServletContext shutdown.
// 如果當前成員變數中不存在WebApplicationContext則建立一個根WebApplicationContext
      if (this.context == null) {
         this.context = createWebApplicationContext(servletContext);
      }
      if (this.context instanceof ConfigurableWebApplicationContext) {
         ConfigurableWebApplicationContext cwac = (ConfigurableWebApplicationContext) this.context;
         if (!cwac.isActive()) {
            // The context has not yet been refreshed -> provide services such as
            // setting the parent context, setting the application context id, etc
            if (cwac.getParent() == null) {
               // The context instance was injected without an explicit parent ->
               // determine parent for root web application context, if any.
//為根WebApplicationContext設定一個父容器
               ApplicationContext parent = loadParentContext(servletContext);
               cwac.setParent(parent);
            }
            configureAndRefreshWebApplicationContext(cwac, servletContext);
         }
      }
  /*將建立好的IoC容器放入到application物件中,並設定key為WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE
   因此,在SpringMVC開發中可以在jsp中通過該key在application物件中獲取到根IoC容器,進而獲取到相應的Bean*/  servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, this.context);

      ClassLoader ccl = Thread.currentThread().getContextClassLoader();
      if (ccl == ContextLoader.class.getClassLoader()) {
         currentContext = this.context;
      }
      else if (ccl != null) {
         currentContextPerThread.put(ccl, this.context);
      }

      if (logger.isDebugEnabled()) {
         logger.debug("Published root WebApplicationContext as ServletContext attribute with name [" +
               WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE + "]");
      }
      if (logger.isInfoEnabled()) {
         long elapsedTime = System.currentTimeMillis() - startTime;
         logger.info("Root WebApplicationContext: initialization completed in " + elapsedTime + " ms");
      }

      return this.context;
   }
   catch (RuntimeException ex) {
      logger.error("Context initialization failed", ex);
      servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, ex);
      throw ex;
   }
   catch (Error err) {
      logger.error("Context initialization failed", err);
      servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, err);
      throw err;
   }
}

initWebApplicationContext()方法如上註解講述,主要目的就是建立root WebApplicationContext物件即根IoC容器,其中比較重要的就是,整個Web應用如果存在根IoC容器則有且只能有一個,根IoC容器作為全域性變數儲存在ServletContextapplication物件中。將根IoC容器放入到application物件之前進行了IoC容器的配置和重新整理操作,呼叫了configureAndRefreshWebApplicationContext()方法,該方法原始碼如下:

protected void configureAndRefreshWebApplicationContext(ConfigurableWebApplicationContext wac, ServletContext sc) {
   if (ObjectUtils.identityToString(wac).equals(wac.getId())) {
      // The application context id is still set to its original default value
      // -> assign a more useful id based on available information
      String idParam = sc.getInitParameter(CONTEXT_ID_PARAM);
      if (idParam != null) {
         wac.setId(idParam);
      }
      else {
         // Generate default id...
         wac.setId(ConfigurableWebApplicationContext.APPLICATION_CONTEXT_ID_PREFIX +
               ObjectUtils.getDisplayString(sc.getContextPath()));
      }
   }

   wac.setServletContext(sc);
/*
        CONFIG_LOCATION_PARAM = "contextConfigLocation"
        獲取web.xml中<context-param>標籤配置的全域性變數,其中key為CONFIG_LOCATION_PARAM
        也就是我們配置的相應Bean的xml檔名,並將其放入到WebApplicationContext中
        */
   String configLocationParam = sc.getInitParameter(CONFIG_LOCATION_PARAM);
   if (configLocationParam != null) {
      wac.setConfigLocation(configLocationParam);
   }

   // The wac environment's #initPropertySources will be called in any case when the context
   // is refreshed; do it eagerly here to ensure servlet property sources are in place for
   // use in any post-processing or initialization that occurs below prior to #refresh
   ConfigurableEnvironment env = wac.getEnvironment();
   if (env instanceof ConfigurableWebEnvironment) {
      ((ConfigurableWebEnvironment) env).initPropertySources(sc, null);
   }

   customizeContext(sc, wac);
   wac.refresh();
}

比較重要的就是獲取到了web.xml中的<context-param>標籤配置的全域性變數contextConfigLocation,並最後一行呼叫了refresh()方法,ConfigurableWebApplicationContext是一個介面,通過對常用實現類ClassPathXmlApplicationContext逐層查詢後可以找到一個抽象類AbstractApplicationContext實現了refresh()方法,其原始碼如下:

@Override
public void refresh() throws BeansException, IllegalStateException {
   synchronized (this.startupShutdownMonitor) {
      // Prepare this context for refreshing.
      prepareRefresh();

      // Tell the subclass to refresh the internal bean factory.
      ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();

      // Prepare the bean factory for use in this context.
      prepareBeanFactory(beanFactory);

      try {
         // Allows post-processing of the bean factory in context subclasses.
         postProcessBeanFactory(beanFactory);

         // Invoke factory processors registered as beans in the context.
         invokeBeanFactoryPostProcessors(beanFactory);

         // Register bean processors that intercept bean creation.
         registerBeanPostProcessors(beanFactory);

         // Initialize message source for this context.
         initMessageSource();

         // Initialize event multicaster for this context.
         initApplicationEventMulticaster();

         // Initialize other special beans in specific context subclasses.
         onRefresh();

         // Check for listener beans and register them.
         registerListeners();

         // Instantiate all remaining (non-lazy-init) singletons.
         finishBeanFactoryInitialization(beanFactory);

         // Last step: publish corresponding event.
         finishRefresh();
      }

      catch (BeansException ex) {
         if (logger.isWarnEnabled()) {
            logger.warn("Exception encountered during context initialization - " +
                  "cancelling refresh attempt: " + ex);
         }

         // Destroy already created singletons to avoid dangling resources.
         destroyBeans();

         // Reset 'active' flag.
         cancelRefresh(ex);

         // Propagate exception to caller.
         throw ex;
      }

      finally {
         // Reset common introspection caches in Spring's core, since we
         // might not ever need metadata for singleton beans anymore...
         resetCommonCaches();
      }
   }
}

該方法主要用於建立並初始化contextConfigLocation類配置的xml檔案中的Bean,因此,如果我們在配置Bean時出錯,在Web應用啟動時就會丟擲異常,而不是等到執行時才丟擲異常

整個ContextLoaderListener類的啟動過程到此就結束了,可以發現,建立ContextLoaderListener是比較核心的一個步驟,主要工作就是為了建立根IoC容器並使用特定的key將其放入到application物件中,供整個Web應用使用,由於在ContextLoaderListener類中構造的根IoC容器配置的Bean是全域性共享的,因此,在<context-param>標識的contextConfigLocation的xml配置檔案一般包括:資料庫DataSource、DAO層、Service層、事務等相關Bean

在JSP中可以通過以下兩種方法獲取到根IoC容器從而獲取相應Bean:

WebApplicationContext applicationContext = (WebApplicationContext) application.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);

 

WebApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicati

 

2.Filter的初始化

在監聽器listener初始化完成後,按照文章開始的講解,接下來會進行filter的初始化操作filter的建立和初始化中沒有涉及IoC容器的相關操作,本文舉例的filter是一個用於編碼使用者請求和響應的過濾器,採用utf-8編碼用於適配中文。

 

3. Servlet的初始化

 Web應用啟動的最後一個步驟就是建立和初始化相關Servlet,在開發中常用的Servlet就是DispatcherServlet類前端控制器,前端控制器作為中央控制器是整個Web應用的核心,用於獲取分發使用者請求並返回響應,借用網上一張關於DispatcherServlet類的類圖,其類圖如下所示:

通過類圖可以看出DispatcherServlet類的間接父類實現了Servlet介面,因此其本質上依舊是一個ServletDispatcherServlet類的設計很巧妙,上層父類不同程度的實現了相關介面的部分方法,並留出了相關方法用於子類覆蓋,將不變的部分統一實現,將變化的部分預留方法用於子類實現。

通過對上述類圖中相關類的原始碼分析可以繪製如下相關初始化方法呼叫邏輯:

通過類圖和相關初始化函式呼叫的邏輯來看,DispatcherServlet類的初始化過程將模板方法使用的淋漓盡致,其父類完成不同的統一的工作,並預留出相關方法用於子類覆蓋去完成不同的可變工作。

DispatcherServelt類的本質是Servlet,通過文章開始的講解可知,在Web應用部署到容器後進行Servlet初始化時會呼叫相關的init(ServletConfig)方法,因此,DispatchServlet類的初始化過程也由該方法開始。上述呼叫邏輯中比較重要的就是FrameworkServlet抽象類中的initServletBean()方法、initWebApplicationContext()方法以及DispatcherServlet類中的onRefresh()方法,接下來會逐一進行講解。

首先檢視一下FrameworkServletinitServletBean()的相關原始碼如下所示:

@Override
protected final void initServletBean() throws ServletException {
   getServletContext().log("Initializing Spring FrameworkServlet '" + getServletName() + "'");
   if (this.logger.isInfoEnabled()) {
      this.logger.info("FrameworkServlet '" + getServletName() + "': initialization started");
   }
   long startTime = System.currentTimeMillis();

   try {
      this.webApplicationContext = initWebApplicationContext();
      initFrameworkServlet();
   }
   catch (ServletException ex) {
      this.logger.error("Context initialization failed", ex);
      throw ex;
   }
   catch (RuntimeException ex) {
      this.logger.error("Context initialization failed", ex);
      throw ex;
   }

   if (this.logger.isInfoEnabled()) {
      long elapsedTime = System.currentTimeMillis() - startTime;
      this.logger.info("FrameworkServlet '" + getServletName() + "': initialization completed in " +
            elapsedTime + " ms");
   }
}

該方法是重寫了FrameworkServlet抽象類父類HttpServletBean抽象類的initServletBean()方法,HttpServletBean抽象類在執行init()方法時會呼叫initServletBean()方法,由於多型的特性,最終會呼叫其子類FrameworkServlet抽象類的initServletBean()方法。該方法由final標識,子類就不可再次重寫了。該方法中比較重要的就是initWebApplicationContext()方法的呼叫,該方法仍由FrameworkServlet抽象類實現,繼續檢視其原始碼如下所示:

/**
 * Initialize and publish the WebApplicationContext for this servlet.
 * <p>Delegates to {@link #createWebApplicationContext} for actual creation
 * of the context. Can be overridden in subclasses.
 * @return the WebApplicationContext instance
 * @see #FrameworkServlet(WebApplicationContext)
 * @see #setContextClass
 * @see #setContextConfigLocation
 */
protected WebApplicationContext initWebApplicationContext() {
   /*
        獲取由ContextLoaderListener建立的根IoC容器
        獲取根IoC容器有兩種方法,還可通過key直接獲取
        */
 WebApplicationContext rootContext =
         WebApplicationContextUtils.getWebApplicationContext(getServletContext());
   WebApplicationContext wac = null;

   if (this.webApplicationContext != null) {
      // A context instance was injected at construction time -> use it
      wac = this.webApplicationContext;
      if (wac instanceof ConfigurableWebApplicationContext) {
         ConfigurableWebApplicationContext cwac = (ConfigurableWebApplicationContext) wac;
         if (!cwac.isActive()) {
            // The context has not yet been refreshed -> provide services such as
            // setting the parent context, setting the application context id, etc
            if (cwac.getParent() == null) {
               // The context instance was injected without an explicit parent -> set
               // the root application context (if any; may be null) as the parent
/*如果當前Servelt存在一個WebApplicationContext即子IoC容器並且上文獲取的根IoC容器存在,則將根IoC容器作為子IoC容器的父容器                 */
               cwac.setParent(rootContext);
            }
//配置並重新整理當前的子IoC容器,功能與前文講解根IoC容器時的配置重新整理一致,用於構建相關Bean
            configureAndRefreshWebApplicationContext(cwac);
         }
      }
   }
   if (wac == null) {
      // No context instance was injected at construction time -> see if one
      // has been registered in the servlet context. If one exists, it is assumed
      // that the parent context (if any) has already been set and that the
      // user has performed any initialization such as setting the context id
//如果當前Servlet不存在一個子IoC容器則去查詢一下
      wac = findWebApplicationContext();
   }
   if (wac == null) {
      // No context instance is defined for this servlet -> create a local one
//如果仍舊沒有查詢到子IoC容器則建立一個子IoC容器
      wac = createWebApplicationContext(rootContext);
   }

   if (!this.refreshEventReceived) {
      // Either the context is not a ConfigurableApplicationContext with refresh
      // support or the context injected at construction time had already been
      // refreshed -> trigger initial onRefresh manually here.
  //呼叫子類覆蓋的onRefresh方法完成“可變”的初始化過程
      onRefresh(wac);
   }

   if (this.publishContext) {
      // Publish the context as a servlet context attribute.
      String attrName = getServletContextAttributeName();
      getServletContext().setAttribute(attrName, wac);
      if (this.logger.isDebugEnabled()) {
         this.logger.debug("Published WebApplicationContext of servlet '" + getServletName() +
               "' as ServletContext attribute with name [" + attrName + "]");
      }
   }

   return wac;
}

通過函式名不難發現,該方法的主要作用同樣是建立一個WebApplicationContext物件,即Ioc容器,不過前文講過每個Web應用最多隻能存在一個IoC容器,這裡建立的則是特定Servlet擁有的IoC容器,可能有些讀者會有疑問,為什麼需要多個Ioc容器,首先介紹一個父子IoC容器的訪問特性,有興趣的讀者可以自行實驗。

 

 

         父子IoC容器的訪問特性

在學習Spring時,我們都是從讀取xml配置檔案來構造IoC容器,常用的類有ClassPathXmlApplicationContext類,該類存在一個初始化方法用於傳入xml檔案路徑以及一個父容器,我們可以建立兩個不同的xml配置檔案並實現如下程式碼:

//applicationContext1.xml檔案中配置一個id為baseBean的Bean
ApplicationContext baseContext = new ClassPathXmlApplicationContext("applicationContext1.xml");
Object obj1 = baseContext.getBean("baseBean");
System.out.println("baseContext Get Bean " + obj1);
//applicationContext2.xml檔案中配置一個id未subBean的Bean
ApplicationContext subContext = new ClassPathXmlApplicationContext(new String[]{"applicationContext2.xml"}, baseContext);
Object obj2 = subContext.getBean("baseBean");
System.out.println("subContext get baseContext Bean " + obj2);
Object obj3 = subContext.getBean("subBean");
System.out.println("subContext get subContext Bean " + obj3);
//丟擲NoSuchBeanDefinitionException異常
Object obj4 = baseContext.getBean("subBean");
System.out.println("baseContext get subContext Bean " + obj4);

首先建立baseContext沒有為其設定父容器,接著可以成功獲取id為baseBean的Bean,接著建立subContext並將baseContext設定為其父容器,subContext可以成功獲取baseBean以及subBean,最後試圖使用baseContext去獲取subContext中定義的subBean,此時會丟擲異常NoSuchBeanDefinitionException,由此可見,父子容器類似於類的繼承關係,子類可以訪問父類中的成員變數,而父類不可訪問子類的成員變量,同樣的,子容器可以訪問父容器中定義的Bean,但父容器無法訪問子容器定義的Bean

通過上述實驗我們可以理解為何需要建立多個Ioc容器,根IoC容器做為全域性共享的IoC容器放入Web應用需要共享的Bean,而子IoC容器根據需求的不同,放入不同的Bean,這樣能夠做到隔離,保證系統的安全性。


接下來繼續講解DispatcherServlet類的IoC容器建立過程,如果當前Servlet存在一個IoC容器則為其設定IoC容器作為其父類,並配置重新整理該容器,用於構造其定義的Bean,這裡的方法與前文講述的IoC容器類似,同樣會讀取使用者在web.xml中配置的<servlet>中的<init-param>值,用於查詢相關的xml配置檔案用於構造定義的Bean,這裡不再贅述了。如果當前Servlet不存在一個IoC容器就去查詢一個,如果仍然沒有查詢到則呼叫
createWebApplicationContext()方法去建立一個,檢視該方法的原始碼如下所示:

/**
 * Instantiate the WebApplicationContext for this servlet, either a default
 * {@link org.springframework.web.context.support.XmlWebApplicationContext}
 * or a {@link #setContextClass custom context class}, if set.
 * <p>This implementation expects custom contexts to implement the
 * {@link org.springframework.web.context.ConfigurableWebApplicationContext}
 * interface. Can be overridden in subclasses.
 * <p>Do not forget to register this servlet instance as application listener on the
 * created context (for triggering its {@link #onRefresh callback}, and to call
 * {@link org.springframework.context.ConfigurableApplicationContext#refresh()}
 * before returning the context instance.
 * @param parent the parent ApplicationContext to use, or {@code null} if none
 * @return the WebApplicationContext for this servlet
 * @see org.springframework.web.context.support.XmlWebApplicationContext
 */
protected WebApplicationContext createWebApplicationContext(ApplicationContext parent) {
   Class<?> contextClass = getContextClass();
   if (this.logger.isDebugEnabled()) {
      this.logger.debug("Servlet with name '" + getServletName() +
            "' will try to create custom WebApplicationContext context of class '" +
            contextClass.getName() + "'" + ", using parent context [" + parent + "]");
   }
   if (!ConfigurableWebApplicationContext.class.isAssignableFrom(contextClass)) {
      throw new ApplicationContextException(
            "Fatal initialization error in servlet with name '" + getServletName() +
            "': custom WebApplicationContext class [" + contextClass.getName() +
            "] is not of type ConfigurableWebApplicationContext");
   }
   ConfigurableWebApplicationContext wac =
         (ConfigurableWebApplicationContext) BeanUtils.instantiateClass(contextClass);

   wac.setEnvironment(getEnvironment());
   wac.setParent(parent);
   wac.setConfigLocation(getContextConfigLocation());

   configureAndRefreshWebApplicationContext(wac);

   return wac;
}

該方法用於建立一個IoC容器並將IoC容器做為其父容器,接著進行配置和重新整理操作用於構造相關的Bean。至此,根IoC容器以及相關ServletIoC容器已經配置完成,子容器中管理的Bean一般只被該Servlet使用,因此,其中管理的Bean一般是“區域性”的,如SpringMVC中需要的各種重要元件,包括ControllerInterceptorConverterExceptionResolver等。相關關係如下圖所示:

IoC子容器構造完成後呼叫了onRefresh()方法,該方法的呼叫與initServletBean()方法的呼叫相同,由父類呼叫但具體實現由子類覆蓋,呼叫onRefresh()方法時將前文建立的IoC子容器作為引數傳入,檢視DispatcherServlet類的onRefresh()方法原始碼如下:

/**
 * This implementation calls {@link #initStrategies}.
 */ //context為DispatcherServlet建立的一個IoC子容器
@Override
protected void onRefresh(ApplicationContext context) {
   initStrategies(context);
}

/**
 * Initialize the strategy objects that this servlet uses.
 * <p>May be overridden in subclasses in order to initialize further strategy objects.
 */
protected void initStrategies(ApplicationContext context) {
   initMultipartResolver(context);
   initLocaleResolver(context);
   initThemeResolver(context);
   initHandlerMappings(context);
   initHandlerAdapters(context);
   initHandlerExceptionResolvers(context);
   initRequestToViewNameTranslator(context);
   initViewResolvers(context);
   initFlashMapManager(context);
}

onRefresh()方法直接呼叫了initStrategies()方法,原始碼如上,通過函式名可以判斷,該方法用於初始化建立multipartResovle來支援圖片等檔案的上傳、本地化解析器、主題解析器、HandlerMapping處理器對映器、HandlerAdapter處理器介面卡、異常解析器、檢視解析器、flashMap管理器等,這些元件都是SpringMVC開發中的重要元件,相關元件的初始化建立過程均在此完成。

至此,DispatcherServlet類的建立和初始化過程也就結束了,整個Web應用部署到容器後的初始化啟動過程的重要部分全部分析清楚了,通過前文的分析我們可以認識到層次化設計的優點,以及IoC容器的繼承關係所表現的隔離性。分析原始碼能讓我們更清楚的理解和認識到相關初始化邏輯以及配置檔案的配置原理。



參考:https://www.jianshu.com/p/dc