深刻分析Spring 與 Spring MVC容器

#0 系列目錄#前端

#1 Spring MVC WEB配置# Spring Framework自己沒有Web功能,Spring MVC使用WebApplicationContext類擴展ApplicationContext,使得擁有web功能。那麼,Spring MVC是如何在web環境中建立IoC容器呢?web環境中的IoC容器的結構又是什麼結構呢?web環境中,Spring IoC容器是怎麼啓動呢?

以Tomcat爲例,在Web容器中使用Spirng MVC,必須進行四項的配置:

  1. 修改web.xml,添加servlet定義;
  2. 編寫servletname-servlet.xml(servletname是在web.xm中配置DispactherServlet時使servlet-name的值)配置;
  3. contextConfigLocation初始化參數、配置ContextLoaderListerner;

Web.xml配置以下

<!-- servlet定義:前端處理器,接受的HTTP請求和轉發請求的類 -->
    <servlet>
        <servlet-name>court</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <!-- court-servlet.xml:定義WebAppliactionContext上下文中的bean -->
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath*:court-servlet.xml</param-value>
        </init-param>
        <load-on-startup>0</load-on-startup>
    </servlet>
             
    <servlet-mapping>
        <servlet-name>court</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
 
    <!-- 配置contextConfigLocation初始化參數:指定Spring IoC容器須要讀取的定義了非web層的Bean(DAO/Service)的XML文件路徑 -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/court-service.xml</param-value>
    </context-param>
 
    <!-- 配置ContextLoaderListerner:Spring MVC在Web容器中的啓動類,負責Spring IoC容器在Web上下文中的初始化 -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

在web.xml配置文件中,有兩個主要的配置:ContextLoaderListener和DispatcherServlet。一樣的關於spring配置文件的相關配置也有兩部分:context-param和DispatcherServlet中的init-param。那麼,這兩部分的配置有什麼區別呢?它們都擔任什麼樣的職責呢?

在Spring MVC中,Spring Context是以父子的繼承結構存在的。Web環境中存在一個ROOT Context,這個Context是整個應用的根上下文,是其餘context的雙親Context。同時Spring MVC也對應的持有一個獨立的Context,它是ROOT Context的子上下文。

對於這樣的Context結構在Spring MVC中是如何實現的呢?下面就先從ROOT Context入手,ROOT Context是在ContextLoaderListener中配置的,ContextLoaderListener讀取context-param中的contextConfigLocation指定的配置文件,建立ROOT Context

Spring MVC啓動過程大體分爲兩個過程:

  1. ContextLoaderListener初始化,實例化IoC容器,並將此容器實例註冊到ServletContext中;
  2. DispatcherServlet初始化;

#2 Web容器中Spring根上下文的加載與初始化# Web容器調用contextInitialized方法初始化ContextLoaderListener,在此方法中,ContextLoaderListener經過調用繼承自ContextLoader的initWebApplicationContext方法實例化Spring Ioc容器

  1. 先看一下WebApplicationContext是如何擴展ApplicationContext來添加對Web環境的支持的。WebApplicationContext接口定義以下:
public interface WebApplicationContext extends ApplicationContext {
        //根上下文在ServletContext中的名稱
        String ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE = WebApplicationContext.class.getName() + ".ROOT";
        //取得web容器的ServletContext
        ServletContext getServletContext();
    }
  1. 下面看一下ContextLoaderListener中建立context的源碼:ContextLoader.java
public WebApplicationContext initWebApplicationContext(ServletContext servletContext) {
        //PS : ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE=WebApplicationContext.class.getName() + ".ROOT" 根上下文的名稱
        //PS : 默認狀況下,配置文件的位置和名稱是: DEFAULT_CONFIG_LOCATION = "/WEB-INF/applicationContext.xml" 
        //在整個web應用中,只能有一個根上下文
        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.
            if (this.context == null) {
                // 在這裏執行了建立WebApplicationContext的操做
                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.
                        ApplicationContext parent = loadParentContext(servletContext);
                        cwac.setParent(parent);
                    }
                    configureAndRefreshWebApplicationContext(cwac, servletContext);
                }
            }
            // PS: 將根上下文放置在servletContext中
            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;
        }
    }
  1. 再看一下WebApplicationContext對象是如何建立的:ContextLoader.java
protected WebApplicationContext createWebApplicationContext(ServletContext sc, ApplicationContext parent) {
        //根據web.xml中的配置決定使用何種WebApplicationContext。默認狀況下使用XmlWebApplicationContext
        //web.xml中相關的配置context-param的名稱「contextClass」
        Class<?> contextClass = determineContextClass(sc);
        if (!ConfigurableWebApplicationContext.class.isAssignableFrom(contextClass)) {
            throw new ApplicationContextException("Custom context class [" + contextClass.getName() + "] is not of type [" + ConfigurableWebApplicationContext.class.getName() + "]");
        }

        //實例化WebApplicationContext的實現類
        ConfigurableWebApplicationContext wac = (ConfigurableWebApplicationContext) BeanUtils.instantiateClass(contextClass);

        // Assign the best possible id value.
        if (sc.getMajorVersion() == 2 && sc.getMinorVersion() < 5) {
	    // Servlet <= 2.4: resort to name specified in web.xml, if any.
            String servletContextName = sc.getServletContextName();
            if (servletContextName != null) {
                wac.setId(ConfigurableWebApplicationContext.APPLICATION_CONTEXT_ID_PREFIX + servletContextName);
            } else {
		wac.setId(ConfigurableWebApplicationContext.APPLICATION_CONTEXT_ID_PREFIX);
            }
        } else {
            // Servlet 2.5's getContextPath available!
            wac.setId(ConfigurableWebApplicationContext.APPLICATION_CONTEXT_ID_PREFIX + sc.getContextPath());
        }

        wac.setParent(parent);

        wac.setServletContext(sc);
        //設置spring的配置文件
        wac.setConfigLocation(sc.getInitParameter(CONFIG_LOCATION_PARAM));
        customizeContext(sc, wac);
        //spring容器初始化
        wac.refresh();
        return wac;
    }
  1. ContextLoaderListener構建Root Context時序圖:

輸入圖片說明

#3 Spring MVC對應的上下文加載與初始化# Spring MVC中核心的類是DispatcherServlet,在這個類中完成Spring context的加載與建立,而且可以根據Spring Context的內容將請求分發給各個Controller類。DispatcherServlet繼承自HttpServlet,關於Spring Context的配置文件加載和建立是在init()方法中進行的,主要的調用順序是init-->initServletBean-->initWebApplicationContext

  1. 先來看一下initWebApplicationContext的實現:FrameworkServlet.java
protected WebApplicationContext initWebApplicationContext() {
        //先從web容器的ServletContext中查找WebApplicationContext
        WebApplicationContext wac = findWebApplicationContext();
        if (wac == null) {
            // No fixed context defined for this servlet - create a local one.
            //從ServletContext中取得根上下文
            WebApplicationContext parent = WebApplicationContextUtils.getWebApplicationContext(getServletContext());
            //建立Spring MVC的上下文,並將根上下文做爲起雙親上下文
            wac = createWebApplicationContext(parent);
        }

        if (!this.refreshEventReceived) {
            // Apparently not a ConfigurableApplicationContext with refresh support:
            // triggering initial onRefresh manually here.
            onRefresh(wac);
        }

        if (this.publishContext) {
            // Publish the context as a servlet context attribute.
            // 取得context在ServletContext中的名稱
            String attrName = getServletContextAttributeName();
            //將Spring MVC的Context放置到ServletContext中
            getServletContext().setAttribute(attrName, wac);
            if (this.logger.isDebugEnabled()) {
                this.logger.debug("Published WebApplicationContext of servlet '" + getServletName() + "' as ServletContext attribute with name [" + attrName + "]");
            }
        }
            return wac;
    }

經過initWebApplicationContext方法的調用,建立了DispatcherServlet對應的context,並將其放置到ServletContext中,這樣就完成了在web容器中構建Spring IoC容器的過程。

  1. DispatcherServlet建立context時序圖:

輸入圖片說明

  1. DispatcherServlet初始化的大致流程:

輸入圖片說明

  1. 控制器DispatcherServlet的類圖及繼承關係:

輸入圖片說明

#4 Spring中DispacherServlet、WebApplicationContext、ServletContext的關係# 要想很好理解這三個上下文的關係,須要先熟悉Spring是怎樣在web容器中啓動起來的。Spring的啓動過程其實就是其IOC容器的啓動過程,對於web程序,IOC容器啓動過程便是創建上下文的過程。

Spring的啓動過程:

  1. 首先,對於一個web應用,其部署在web容器中,web容器提供其一個全局的上下文環境,這個上下文就是ServletContext,其爲後面的spring IoC容器提供宿主環境;

  2. 其次,在web.xml中會提供有contextLoaderListener。在web容器啓動時,會觸發容器初始化事件,此時contextLoaderListener會監聽到這個事件,其contextInitialized方法會被調用,在這個方法中,spring會初始化一個啓動上下文,這個上下文被稱爲根上下文,即WebApplicationContext,這是一個接口類,確切的說,其實際的實現類是XmlWebApplicationContext。這個就是spring的IoC容器,其對應的Bean定義的配置由web.xml中的context-param標籤指定。在這個IoC容器初始化完畢後,spring以WebApplicationContext.ROOTWEBAPPLICATIONCONTEXTATTRIBUTE爲屬性Key,將其存儲到ServletContext中,便於獲取;

  3. 再次,contextLoaderListener監聽器初始化完畢後,開始初始化web.xml中配置的Servlet,這個servlet能夠配置多個,以最多見的DispatcherServlet爲例,這個servlet其實是一個標準的前端控制器,用以轉發、匹配、處理每一個servlet請求。DispatcherServlet上下文在初始化的時候會創建本身的IoC上下文,用以持有spring mvc相關的bean。在創建DispatcherServlet本身的IoC上下文時,會利用WebApplicationContext.ROOTWEBAPPLICATIONCONTEXTATTRIBUTE先從ServletContext中獲取以前的根上下文(即WebApplicationContext)做爲本身上下文的parent上下文。有了這個parent上下文以後,再初始化本身持有的上下文。這個DispatcherServlet初始化本身上下文的工做在其initStrategies方法中能夠看到,大概的工做就是初始化處理器映射、視圖解析等。這個servlet本身持有的上下文默認實現類也是mlWebApplicationContext。初始化完畢後,spring以與servlet的名字相關(此處不是簡單的以servlet名爲Key,而是經過一些轉換,具體可自行查看源碼)的屬性爲屬性Key,也將其存到ServletContext中,以便後續使用。這樣每一個servlet就持有本身的上下文,即擁有本身獨立的bean空間,同時各個servlet共享相同的bean,即根上下文(第2步中初始化的上下文)定義的那些bean

在Web容器(好比Tomcat)中配置Spring時,你可能已經司空見慣於web.xml文件中的如下配置代碼:

<context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/applicationContext.xml</param-value>
    </context-param>
                                                                                                                                             
    <listener>
        <listener-class>
            org.springframework.web.context.ContextLoaderListener
        </listener-class>
    </listener>
                                                                                                                                             
    <servlet>
        <servlet-name>mvc-dispatcher</servlet-name>
        <servlet-class>
            org.springframework.web.servlet.DispatcherServlet
        </servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
                                                                                                                                         
    <servlet-mapping>
        <servlet-name>mvc-dispatcher</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping></span>

以上配置首先會在ContextLoaderListener中經過<context-param>中的applicationContext.xml建立一個ApplicationContext,再將這個ApplicationContext塞到ServletContext裏面,經過ServletContext的setAttribute方法達到此目的,在ContextLoaderListener的源代碼中,咱們能夠看到這樣的代碼:

servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, this.context);

以上由ContextLoaderListener建立的ApplicationContext是共享於整個Web應用程序的,而你可能早已經知道,DispatcherServlet會維持一個本身的ApplicationContext,默認會讀取/WEB-INFO/<dispatcherServletName>-servlet.xml文件,而也能夠從新配置:

<servlet>  
        <servlet-name>  
           customConfiguredDispacherServlet  
        </servlet-name>  
        <servlet-class>  
            org.springframework.web.servlet.DispatcherServlet  
        </servlet-class>  
        <init-param>  
            <param-name>  
                contextConfigLocation  
            </param-name>  
            <param-value>  
                /WEB-INF/dispacherServletContext.xml  
            </param-value>  
        </init-param>  
        <load-on-startup>1</load-on-startup>  
    </servlet>

問題是:以上兩個ApplicationContext的關係是什麼,它們的做用做用範圍分別是什麼,它們的用途分別是什麼?

ContextLoaderListener中建立ApplicationContext主要用於整個Web應用程序須要共享的一些組件,好比DAO,數據庫的ConnectionFactory等。而由DispatcherServlet建立的ApplicationContext主要用於和該Servlet相關的一些組件,好比Controller、ViewResovler等。

對於做用範圍而言,在DispatcherServlet中能夠引用由ContextLoaderListener所建立的ApplicationContext,而反過來不行。

在Spring的具體實現上,這兩個ApplicationContext都是經過ServletContext的setAttribute方法放到ServletContext中的。可是,ContextLoaderListener會先於DispatcherServlet建立ApplicationContext,DispatcherServlet在建立ApplicationContext時會先找到由ContextLoaderListener所建立的ApplicationContext,再將後者的ApplicationContext做爲參數傳給DispatcherServlet的ApplicationContext的setParent()方法,在Spring源代碼中,你能夠在FrameServlet.java中找到以下代碼:

wac.setParent(parent);

其中,wac即爲由DisptcherServlet建立的ApplicationContext,而parent則爲有ContextLoaderListener建立的ApplicationContext。此後,框架又會調用ServletContext的setAttribute()方法將wac加入到ServletContext中。

當Spring在執行ApplicationContext的getBean時,若是在本身context中找不到對應的bean,則會在父ApplicationContext中去找。這也解釋了爲何咱們能夠在DispatcherServlet中獲取到由ContextLoaderListener對應的ApplicationContext中的bean。

相關文章
相關標籤/搜索