SpringMVC 啟動流程及相關(guān)源碼分析

你要知道的SpringMVC啟動流程和源碼分析都在這里

轉(zhuǎn)載請注明出處 http://www.lxweimin.com/p/dc64d02e49ac

本系列文章主要根據(jù)源碼講解SpringMVC的啟動過程,以及相關(guān)重要組件的源碼分析。閱讀此系列文章需要具備Spring以及SpringMVC相關(guān)知識。本文將分以下幾篇文章進(jìn)行講解,讀者可按需查閱。

SpringMVC 啟動流程及相關(guān)源碼分析

熟悉SpringMVC的啟動過程,有助于我們理解相關(guān)文件配置的原理,深入理解SpringMVC的設(shè)計原理和執(zhí)行過程。

Web應(yīng)用部署初始化過程 (Web Application Deployement)

參考Oracle官方文檔Java Servlet Specification,可知Web應(yīng)用部署的相關(guān)步驟如下:

web應(yīng)用部署流程

當(dāng)一個Web應(yīng)用部署到容器內(nèi)時(eg.tomcat),在Web應(yīng)用開始響應(yīng)執(zhí)行用戶請求前,以下步驟會被依次執(zhí)行:

  • 部署描述文件中(eg.tomcat的web.xml)由<listener>元素標(biāo)記的事件監(jiān)聽器會被創(chuàng)建和初始化
  • 對于所有事件監(jiān)聽器,如果實現(xiàn)了ServletContextListener接口,將會執(zhí)行其實現(xiàn)的contextInitialized()方法
  • 部署描述文件中由<filter>元素標(biāo)記的過濾器會被創(chuàng)建和初始化,并調(diào)用其init()方法
  • 部署描述文件中由<servlet>元素標(biāo)記的servlet會根據(jù)<load-on-startup>的權(quán)值按順序創(chuàng)建和初始化,并調(diào)用其init()方法

通過上述官方文檔的描述,可繪制如下Web應(yīng)用部署初始化流程執(zhí)行圖。

Web應(yīng)用部署初始化流程圖

可以發(fā)現(xiàn),在tomcatweb應(yīng)用的初始化流程是,先初始化listener接著初始化filter最后初始化servlet,當(dāng)我們清楚認(rèn)識到Web應(yīng)用部署到容器后的初始化過程后,就可以進(jìn)一步深入探討SpringMVC的啟動過程。

Spring MVC啟動過程

接下來以一個常見的簡單web.xml配置進(jìn)行Spring MVC啟動過程的分析,web.xml配置內(nèi)容如下:

<web-app>

  <display-name>Web Application</display-name>

  <!--全局變量配置-->
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:applicationContext-*.xml</param-value>
  </context-param>

  <!--監(jiān)聽器-->
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  
  <!--解決亂碼問題的filter-->
  <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>
  </filter>

  <filter-mapping>
    <filter-name>CharacterEncodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

  <!--Restful前端控制器-->
  <servlet>
    <servlet-name>springMVC_rest</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:spring-mvc.xml</param-value>
    </init-param>
  </servlet>

  <servlet-mapping>
    <servlet-name>springMVC_rest</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>

</web-app>

Listener的初始化過程

首先定義了<context-param>標(biāo)簽,用于配置一個全局變量,<context-param>標(biāo)簽的內(nèi)容讀取后會被放進(jìn)application中,做為Web應(yīng)用的全局變量使用,接下來創(chuàng)建listener時會使用到這個全局變量,因此,Web應(yīng)用在容器中部署后,進(jìn)行初始化時會先讀取這個全局變量,之后再進(jìn)行上述講解的初始化啟動過程。

接著定義了一個ContextLoaderListener類listener。查看ContextLoaderListener的類聲明源碼如下圖:

ContextLoaderListener類聲明源碼

ContextLoaderListener類繼承了ContextLoader類并實現(xiàn)了ServletContextListener接口,首先看一下前面講述的ServletContextListener接口源碼:

ServletContextListener接口源碼

該接口只有兩個方法contextInitializedcontextDestroyed,這里采用的是觀察者模式,也稱為為訂閱-發(fā)布模式,實現(xiàn)了該接口的listener會向發(fā)布者進(jìn)行訂閱,當(dāng)Web應(yīng)用初始化或銷毀時會分別調(diào)用上述兩個方法。

繼續(xù)看ContextLoaderListener,該listener實現(xiàn)了ServletContextListener接口,因此在Web應(yīng)用初始化時會調(diào)用該方法,該方法的具體實現(xiàn)如下:

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

ContextLoaderListenercontextInitialized()方法直接調(diào)用了initWebApplicationContext()方法,這個方法是繼承自ContextLoader類,通過函數(shù)名可以知道,該方法是用于初始化Web應(yīng)用上下文,即IoC容器,這里使用的是代理模式,繼續(xù)查看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
     */
    //servletContext,servlet上下文,即application對象
    public WebApplicationContext initWebApplicationContext(ServletContext servletContext) {
    /*
    首先通過WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE
    這個String類型的靜態(tài)變量獲取一個根IoC容器,根IoC容器作為全局變量
    存儲在application對象中,如果存在則有且只能有一個
    如果在初始化根WebApplicationContext即根IoC容器時發(fā)現(xiàn)已經(jīng)存在
    則直接拋出異常,因此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.
            // 如果當(dāng)前成員變量中不存在WebApplicationContext則創(chuàng)建一個根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設(shè)置一個父容器
                        ApplicationContext parent = loadParentContext(servletContext);
                        cwac.setParent(parent);
                    }
                    //配置并刷新整個根IoC容器,在這里會進(jìn)行Bean的創(chuàng)建和初始化
                    configureAndRefreshWebApplicationContext(cwac, servletContext);
                }
            }
            /*
            將創(chuàng)建好的IoC容器放入到application對象中,并設(shè)置key為WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE
            因此,在SpringMVC開發(fā)中可以在jsp中通過該key在application對象中獲取到根IoC容器,進(jìn)而獲取到相應(yīng)的Ben
            */
            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()方法如上注解講述,主要目的就是創(chuàng)建root WebApplicationContext對象根IoC容器,其中比較重要的就是,整個Web應(yīng)用如果存在根IoC容器則有且只能有一個,根IoC容器作為全局變量存儲在ServletContextapplication對象中。將根IoC容器放入到application對象之前進(jìn)行了IoC容器的配置和刷新操作,調(diào)用了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>標(biāo)簽配置的全局變量,其中key為CONFIG_LOCATION_PARAM
        也就是我們配置的相應(yīng)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>標(biāo)簽配置的全局變量contextConfigLocation,并最后一行調(diào)用了refresh()方法,ConfigurableWebApplicationContext是一個接口,通過對常用實現(xiàn)類ClassPathXmlApplicationContext逐層查找后可以找到一個抽象類AbstractApplicationContext實現(xiàn)了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();
            }
        }
    }

該方法主要用于創(chuàng)建并初始化contextConfigLocation類配置的xml文件中的Bean,因此,如果我們在配置Bean時出錯,在Web應(yīng)用啟動時就會拋出異常,而不是等到運行時才拋出異常。

整個ContextLoaderListener類的啟動過程到此就結(jié)束了,可以發(fā)現(xiàn),創(chuàng)建ContextLoaderListener是比較核心的一個步驟,主要工作就是為了創(chuàng)建根IoC容器并使用特定的key將其放入到application對象中,供整個Web應(yīng)用使用,由于在ContextLoaderListener類中構(gòu)造的根IoC容器配置的Bean是全局共享的,因此,在<context-param>標(biāo)識的contextConfigLocationxml配置文件一般包括:數(shù)據(jù)庫DataSourceDAO層、Service層、事務(wù)等相關(guān)Bean。

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

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

WebApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContext(getServletContext());

Filter的初始化

在監(jiān)聽器listener初始化完成后,按照文章開始的講解,接下來會進(jìn)行filter的初始化操作,filter的創(chuàng)建和初始化中沒有涉及IoC容器的相關(guān)操作,因此不是本文講解的重點,本文舉例的filter是一個用于編碼用戶請求和響應(yīng)的過濾器,采用utf-8編碼用于適配中文。

Servlet的初始化

Web應(yīng)用啟動的最后一個步驟就是創(chuàng)建和初始化相關(guān)Servlet,在開發(fā)中常用的Servlet就是DispatcherServlet類前端控制器,前端控制器作為中央控制器是整個Web應(yīng)用的核心,用于獲取分發(fā)用戶請求并返回響應(yīng),借用網(wǎng)上一張關(guān)于DispatcherServlet類的類圖,其類圖如下所示:

DispatcherServlet類圖

通過類圖可以看出DispatcherServlet類的間接父類實現(xiàn)了Servlet接口,因此其本質(zhì)上依舊是一個ServletDispatcherServlet類的設(shè)計很巧妙,上層父類不同程度的實現(xiàn)了相關(guān)接口的部分方法,并留出了相關(guān)方法用于子類覆蓋,將不變的部分統(tǒng)一實現(xiàn),將變化的部分預(yù)留方法用于子類實現(xiàn),本文關(guān)注的是DispatcherServelt類的初始化過程,沒有深入探討其如何對用戶請求做出響應(yīng),讀者有興趣可以閱讀本系列文章的第二篇SpringMVC DispatcherServlet源碼分析

通過對上述類圖中相關(guān)類的源碼分析可以繪制如下相關(guān)初始化方法調(diào)用邏輯:

DispatcherServlet類初始化過程函數(shù)調(diào)用

通過類圖和相關(guān)初始化函數(shù)調(diào)用的邏輯來看,DispatcherServlet類的初始化過程將模板方法使用的淋漓盡致,其父類完成不同的統(tǒng)一的工作,并預(yù)留出相關(guān)方法用于子類覆蓋去完成不同的可變工作。

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

首先查看一下initServletBean()的相關(guān)源碼如下圖所示:

FrameworkServlet initServletBean()方法源碼

該方法是重寫了FrameworkServlet抽象類父類HttpServletBean抽象類initServletBean()方法,HttpServletBean抽象類在執(zhí)行init()方法時會調(diào)用initServletBean()方法,由于多態(tài)的特性,最終會調(diào)用其子類FrameworkServlet抽象類initServletBean()方法。該方法由final標(biāo)識,子類就不可再次重寫了。該方法中比較重要的就是initWebApplicationContext()方法的調(diào)用,該方法仍由FrameworkServlet抽象類實現(xiàn),繼續(xù)查看其源碼如下所示:

    /**
     * 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創(chuàng)建的根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
                        /*
                        如果當(dāng)前Servelt存在一個WebApplicationContext即子IoC容器
                        并且上文獲取的根IoC容器存在,則將根IoC容器作為子IoC容器的父容器
                        */
                        cwac.setParent(rootContext);
                    }
                    //配置并刷新當(dāng)前的子IoC容器,功能與前文講解根IoC容器時的配置刷新一致,用于構(gòu)建相關(guān)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
            //如果當(dāng)前Servlet不存在一個子IoC容器則去查找一下
            wac = findWebApplicationContext();
        }
        if (wac == null) {
            // No context instance is defined for this servlet -> create a local one
            //如果仍舊沒有查找到子IoC容器則創(chuàng)建一個子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.
            //調(diào)用子類覆蓋的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;
    }

通過函數(shù)名不難發(fā)現(xiàn),該方法的主要作用同樣是創(chuàng)建一個WebApplicationContext對象,即Ioc容器,不過前文講過每個Web應(yīng)用最多只能存在一個根IoC容器,這里創(chuàng)建的則是特定Servlet擁有的子IoC容器,可能有些讀者會有疑問,為什么需要多個Ioc容器,首先介紹一個父子IoC容器的訪問特性,有興趣的讀者可以自行實驗。


父子IoC容器的訪問特性

在學(xué)習(xí)Spring時,我們都是從讀取xml配置文件來構(gòu)造IoC容器,常用的類有ClassPathXmlApplicationContext類,該類存在一個初始化方法用于傳入xml文件路徑以及一個父容器,我們可以創(chuàng)建兩個不同的xml配置文件并實現(xiàn)如下代碼:

//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);

首先創(chuàng)建baseContext沒有為其設(shè)置父容器,接著可以成功獲取idbaseBeanBean,接著創(chuàng)建subContext并將baseContext設(shè)置為其父容器,subContext可以成功獲取baseBean以及subBean,最后試圖使用baseContext去獲取subContext中定義的subBean,此時會拋出異常NoSuchBeanDefinitionException,由此可見,父子容器類似于類的繼承關(guān)系,子類可以訪問父類中的成員變量,而父類不可訪問子類的成員變量,同樣的,子容器可以訪問父容器中定義的Bean,但父容器無法訪問子容器定義的Bean。

通過上述實驗我們可以理解為何需要創(chuàng)建多個Ioc容器,根IoC容器做為全局共享的IoC容器放入Web應(yīng)用需要共享的Bean,而子IoC容器根據(jù)需求的不同,放入不同的Bean,這樣能夠做到隔離,保證系統(tǒng)的安全性。


接下來繼續(xù)講解DispatcherServlet類子IoC容器創(chuàng)建過程,如果當(dāng)前Servlet存在一個IoC容器則為其設(shè)置根IoC容器作為其父類,并配置刷新該容器,用于構(gòu)造其定義的Bean,這里的方法與前文講述的根IoC容器類似,同樣會讀取用戶在web.xml中配置的<servlet>中的<init-param>值,用于查找相關(guān)的xml配置文件用于構(gòu)造定義的Bean,這里不再贅述了。如果當(dāng)前Servlet不存在一個子IoC容器就去查找一個,如果仍然沒有查找到則調(diào)用
createWebApplicationContext()方法去創(chuàng)建一個,查看該方法的源碼如下圖所示:

createWebApplicationContext方法源碼

該方法用于創(chuàng)建一個子IoC容器并將根IoC容器做為其父容器,接著進(jìn)行配置和刷新操作用于構(gòu)造相關(guān)的Bean。至此,根IoC容器以及相關(guān)Servlet子IoC容器已經(jīng)配置完成,子容器中管理的Bean一般只被該Servlet使用,因此,其中管理的Bean一般是“局部”的,如SpringMVC中需要的各種重要組件,包括ControllerInterceptorConverter、ExceptionResolver等。相關(guān)關(guān)系如下圖所示:

父子容器管理Bean類型

當(dāng)IoC子容器構(gòu)造完成后調(diào)用了onRefresh()方法,該方法的調(diào)用與initServletBean()方法的調(diào)用相同,由父類調(diào)用但具體實現(xiàn)由子類覆蓋,調(diào)用onRefresh()方法時將前文創(chuàng)建的IoC子容器作為參數(shù)傳入,查看DispatcherServletBean類onRefresh()方法源碼如下:

    /**
     * This implementation calls {@link #initStrategies}.
     */
    //context為DispatcherServlet創(chuàng)建的一個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()方法直接調(diào)用了initStrategies()方法,源碼如上,通過函數(shù)名可以判斷,該方法用于初始化創(chuàng)建multipartResovle來支持圖片等文件的上傳、本地化解析器、主題解析器、HandlerMapping處理器映射器、HandlerAdapter處理器適配器、異常解析器、視圖解析器、flashMap管理器等,這些組件都是SpringMVC開發(fā)中的重要組件,相關(guān)組件的初始化創(chuàng)建過程均在此完成。

由于篇幅問題本文不再進(jìn)行更深入的探討,有興趣的讀者可以閱讀本系列文章的其他博客內(nèi)容。

至此,DispatcherServlet類的創(chuàng)建和初始化過程也就結(jié)束了,整個Web應(yīng)用部署到容器后的初始化啟動過程的重要部分全部分析清楚了,通過前文的分析我們可以認(rèn)識到層次化設(shè)計的優(yōu)點,以及IoC容器的繼承關(guān)系所表現(xiàn)的隔離性。分析源碼能讓我們更清楚的理解和認(rèn)識到相關(guān)初始化邏輯以及配置文件的配置原理。

總結(jié)

這里給出一個簡潔的文字描述版SpringMVC啟動過程:

tomcat web容器啟動時會去讀取web.xml這樣的部署描述文件,相關(guān)組件啟動順序為: 解析<context-param> => 解析<listener> => 解析<filter> => 解析<servlet>,具體初始化過程如下:

  • 1、解析<context-param>里的鍵值對。

  • 2、創(chuàng)建一個application內(nèi)置對象即ServletContext,servlet上下文,用于全局共享。

  • 3、將<context-param>的鍵值對放入ServletContextapplication中,Web應(yīng)用內(nèi)全局共享。

  • 4、讀取<listener>標(biāo)簽創(chuàng)建監(jiān)聽器,一般會使用ContextLoaderListener類,如果使用了ContextLoaderListener類,Spring就會創(chuàng)建一個WebApplicationContext類的對象,WebApplicationContext類就是IoC容器,ContextLoaderListener類創(chuàng)建的IoC容器根IoC容器為全局性的,并將其放置在appication中,作為應(yīng)用內(nèi)全局共享,鍵名為WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE,可以通過以下兩種方法獲取

    WebApplicationContext applicationContext = (WebApplicationContext) application.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
    
    WebApplicationContext applicationContext1 = WebApplicationContextUtils.getWebApplicationContext(application);
    

這個全局的根IoC容器只能獲取到在該容器中創(chuàng)建的Bean不能訪問到其他容器創(chuàng)建的Bean,也就是讀取web.xml配置的contextConfigLocation參數(shù)的xml文件來創(chuàng)建對應(yīng)的Bean。

  • 5、listener創(chuàng)建完成后如果有<filter>則會去創(chuàng)建filter
  • 6、初始化創(chuàng)建<servlet>,一般使用DispatchServlet類。
  • 7、DispatchServlet的父類FrameworkServlet會重寫其父類的initServletBean方法,并調(diào)用initWebApplicationContext()以及onRefresh()方法。
  • 8、initWebApplicationContext()方法會創(chuàng)建一個當(dāng)前servlet的一個IoC子容器,如果存在上述的全局WebApplicationContext則將其設(shè)置為父容器,如果不存在上述全局的則父容器為null。
  • 9、讀取<servlet>標(biāo)簽的<init-param>配置的xml文件并加載相關(guān)Bean。
  • 10、onRefresh()方法創(chuàng)建Web應(yīng)用相關(guān)組件。

備注

由于作者水平有限,難免出現(xiàn)紕漏,如有問題還請不吝賜教。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 227,882評論 6 531
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 98,208評論 3 414
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 175,746評論 0 373
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經(jīng)常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 62,666評論 1 309
  • 正文 為了忘掉前任,我火速辦了婚禮,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當(dāng)我...
    茶點故事閱讀 71,477評論 6 407
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 54,960評論 1 321
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,047評論 3 440
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 42,200評論 0 288
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 48,726評論 1 333
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 40,617評論 3 354
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 42,807評論 1 369
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,327評論 5 358
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 44,049評論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,425評論 0 26
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,674評論 1 281
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,432評論 3 390
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 47,769評論 2 372

推薦閱讀更多精彩內(nèi)容

  • 從三月份找實習(xí)到現(xiàn)在,面了一些公司,掛了不少,但最終還是拿到小米、百度、阿里、京東、新浪、CVTE、樂視家的研發(fā)崗...
    時芥藍(lán)閱讀 42,314評論 11 349
  • 1. Java基礎(chǔ)部分 基礎(chǔ)部分的順序:基本語法,類相關(guān)的語法,內(nèi)部類的語法,繼承相關(guān)的語法,異常的語法,線程的語...
    子非魚_t_閱讀 31,709評論 18 399
  • Spring容器高層視圖 Spring 啟動時讀取應(yīng)用程序提供的Bean配置信息,并在Spring容器中生成一份相...
    Theriseof閱讀 2,829評論 1 24
  • 什么是Spring Spring是一個開源的Java EE開發(fā)框架。Spring框架的核心功能可以應(yīng)用在任何Jav...
    jemmm閱讀 16,500評論 1 133
  • 佛光星云(1927--) 愛就是惜,惜情、惜緣、愛惜青春; 愛就是惜,奉獻(xiàn)、喜舍、發(fā)揮熱情。 愛就是惜,無怨無恨,...
    元吉利貞閱讀 339評論 0 1