最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

淺談Spring與SpringMVC父子容器的關(guān)系與初始化

 更新時間:2020年08月27日 11:27:25   作者:菜到懷疑人生  
這篇文章主要介紹了淺談Spring與SpringMVC父子容器的關(guān)系與初始化,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧

Spring和SpringMVC的容器具有父子關(guān)系,Spring容器為父容器,SpringMVC為子容器,子容器可以引用父容器中的Bean,而父容器不可以引用子容器中的Bean。

了解了Spring與SpringMVC父子容器的關(guān)系,接下來讓我們看看Spring與SpringMVC容器的初始化過程。

以下講解使用的web.xml文件如下:

 <context-param>
    <param-name>contextConfigLocation</param-name>//指定spring ioc配置文件的位置
    <param-value>classpath*:spring/*.xml</param-value>
  </context-param>
  <!-- Creates the Spring Container shared by all Servlets and Filters -->
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
<!-- 配置DisaptcherServlet -->
  <servlet>
    <servlet-name>springMVC</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <!-- 初始化參數(shù),配置springmvc配置文件 -->
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>springMVC配置文件的路徑</param-value>
    </init-param>
    <!-- web容器啟動時加載該Servlet -->
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>springMVC</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>

spring ioc容器初始化的過程

1、web應(yīng)用程序啟動時,tomcat會讀取web.xml文件中的context-parm(含有配置文件的路徑)和listener節(jié)點,接著會為應(yīng)用程序創(chuàng)建一個ServletContext,為全局共享,Spring ioc容器就是存儲在這里

2、tomcat將context-param節(jié)點轉(zhuǎn)換為鍵值對,寫入到ServletContext中

3、創(chuàng)建listener節(jié)點中的ContextLoaderListener實例,調(diào)用該實例,初始化webapplicationContext,這是一個接口,其實現(xiàn)類為XmlWebApplicationContext(即spring的IOC容器),其通過ServletContext.getinitialParameter("contextConfigLoaction")從ServletContext中獲取context-param中的值(即spring ioc容器配置文件的路徑),這就是為什么要有第二步的原因。接著根據(jù)配置文件的路徑加載配置文件信息(其中含有Bean的配置信息)到WebApplicationContext(即spring ioc容器)中,將WebApplicationContext以WebApplicationContext.ROOTWEBAPPLICATIONCONTEXTATTRIBUTE為屬性Key,將其存儲到ServletContext中,便于獲取。至此,spring ioc容器初始化完畢

4、容器初始化web.xml中配置的servlet,為其初始化自己的上下文信息servletContext,并加載其設(shè)置的配置信息到該上下文中。將WebApplicationContext(即spring ioc容器)設(shè)置為它的父容器。其中便有SpringMVC(假設(shè)配置了SpringMVC),這就是為什么spring ioc是springmvc ioc的父容器的原因

SpringMVC初始化過程

SpringMVC通過web.xml文件中servlet標(biāo)簽下的DispatcherServlet類完成自身的初始化

DispatcherServlet類的繼承體系如下:

請注意每個長方形中第三行的方法,其為完成SpringMVC ioc容器初始化的關(guān)鍵。

我們知道,每個servlet在初始化時,會先調(diào)用servlte的構(gòu)造函數(shù)(為默認(rèn)構(gòu)造函數(shù)),接著調(diào)用init函數(shù),而DispatcherServlet的init方法在其父類HttpServlet中。

HttpServlet中的init方法

/DispatcherServlet第一次加載時調(diào)用init方法
@Override
  public final void init() throws ServletException {
    if (logger.isDebugEnabled()) {
      logger.debug("Initializing servlet '" + getServletName() + "'");
    }
    // Set bean properties from init parameters.
    try {
/*加載web.xml文件中的servlet標(biāo)簽中的init-param,其中含有springMVC的配置文件的名字和路徑
 *若沒有,則默認(rèn)為(servlet-name)-servlet.xml,
 *默認(rèn)路徑為WEF—INF下
 */
      PropertyValues pvs = new ServletConfigPropertyValues(getServletConfig(), this.requiredProperties);
     //創(chuàng)建BeanWrapper實例,為DispatcherServlet設(shè)置屬性
      BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(this);
      ResourceLoader resourceLoader = new ServletContextResourceLoader(getServletContext());
      bw.registerCustomEditor(Resource.class, new ResourceEditor(resourceLoader, getEnvironment()));
      initBeanWrapper(bw);
     //把init-param中的參數(shù)設(shè)置到DispatcherServlet里面去
      bw.setPropertyValues(pvs, true);
    }
    catch (BeansException ex) {
      logger.error("Failed to set bean properties on servlet '" + getServletName() + "'", ex);
      throw ex;
    }
 
 
    // Let subclasses do whatever initialization they like.
    //該方法在FrameworkServlet中
    initServletBean();
 
 
    if (logger.isDebugEnabled()) {
      logger.debug("Servlet '" + getServletName() + "' configured successfully");
    }
  }

FrameworkServlet中的initServletBean方法

@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 {
      //創(chuàng)建springmvc的ioc容器實例
      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中的initWebapplicationContext方法

protected WebApplicationContext initWebApplicationContext() {
    //首先通過ServletContext獲得spring容器,因為子容器springMVC要和父容器spring容器進(jìn)行關(guān)聯(lián)
    //這就是為什么要在ServletContext中注冊spring ioc容器的原因
    WebApplicationContext rootContext =
        WebApplicationContextUtils.getWebApplicationContext(getServletContext());
    //定義springMVC容器wac
    WebApplicationContext wac = null;
 
 
    //判斷容器是否由編程式傳入(即是否已經(jīng)存在了容器實例),存在的話直接賦值給wac,給springMVC容器設(shè)置父容器
    //最后調(diào)用刷新函數(shù)configureAndRefreshWebApplicationContext(wac),作用是把springMVC的配置信息加載到容器中去(之前已經(jīng)將配置信息的路徑設(shè)置到了bw中)
    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()) {
 
 
          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
            //將spring ioc設(shè)置為springMVC ioc的父容器
            cwac.setParent(rootContext);
          }
 
 
          configureAndRefreshWebApplicationContext(cwac);
        }
      }
    }
    if (wac == null) {
      // 在ServletContext中尋找是否有springMVC容器,初次運行是沒有的,springMVC初始化完畢ServletContext就有了springMVC容器
      wac = findWebApplicationContext();
    }
 
 
    //當(dāng)wac既沒有沒被編程式注冊到容器中的,也沒在ServletContext找得到,此時就要新建一個springMVC容器
    if (wac == null) {
      // 創(chuàng)建springMVC容器
      wac = createWebApplicationContext(rootContext);
    }
 
 
    if (!this.refreshEventReceived) {
      //到這里mvc的容器已經(jīng)創(chuàng)建完畢,接著才是真正調(diào)用DispatcherServlet的初始化方法onRefresh(wac)
      onRefresh(wac);
    }
 
 
    if (this.publishContext) {
      //將springMVC容器存放到ServletContext中去,方便下次取出來
      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;
  }

FrameworkServlet中的createWebApplicationContext(WebApplicationContext parent)方法

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");
    }
    //實例化空白的ioc容器
    ConfigurableWebApplicationContext wac =
        (ConfigurableWebApplicationContext) BeanUtils.instantiateClass(contextClass);
    //給容器設(shè)置環(huán)境
    wac.setEnvironment(getEnvironment());
    //給容器設(shè)置父容器(就是spring容器),兩個ioc容器關(guān)聯(lián)在一起了
    wac.setParent(parent);
    //給容器加載springMVC的配置信息,之前已經(jīng)通過bw將配置文件路徑寫入到了DispatcherServlet中
    wac.setConfigLocation(getContextConfigLocation());
    //上面提到過這方法,刷新容器,根據(jù)springMVC配置文件完成初始化操作,此時springMVC容器創(chuàng)建完成
    configureAndRefreshWebApplicationContext(wac);
 
    return wac;
  }

DispatcherServlet的onRefresh(ApplicationContext context)方法

@Override
  protected void onRefresh(ApplicationContext context) {
    initStrategies(context);
  }

DispatcherServlet的initStrategies(ApplicationContext context)方法

protected void initStrategies(ApplicationContext context) {
    initMultipartResolver(context);//文件上傳解析
    initLocaleResolver(context);//本地解析
    initThemeResolver(context);//主題解析
    initHandlerMappings(context);//url請求映射
    initHandlerAdapters(context);//初始化真正調(diào)用controloler方法的類
    initHandlerExceptionResolvers(context);//異常解析
    initRequestToViewNameTranslator(context);
    initViewResolvers(context);//視圖解析
    initFlashMapManager(context);
  }

總結(jié)以下DispatcherServlet及各個父類(接口)的功能:

HttpServlet:實現(xiàn)了init方法,完成web,xml中與DispatcherServlet有關(guān)的參數(shù)的讀入,初始化DispatcherServlet。

FrameworkServlet:完成了springMVC ioc 容器的創(chuàng)建,并且將spring ioc容器設(shè)置為springMVC ioc容器的父容器,將springMVC ioc容器注冊到ServletContext中

DispatcherServlet:完成策略組件的初始化

至此,SpringMVC容器初始化完成

以上這篇淺談Spring與SpringMVC父子容器的關(guān)系與初始化就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。

相關(guān)文章

  • spring mvc 實現(xiàn)獲取后端傳遞的值操作示例

    spring mvc 實現(xiàn)獲取后端傳遞的值操作示例

    這篇文章主要介紹了spring mvc 實現(xiàn)獲取后端傳遞的值操作,結(jié)合實例形式詳細(xì)分析了spring mvc使用JSTL 方法獲取后端傳遞的值相關(guān)操作技巧
    2019-11-11
  • springboot更新配置Swagger3的一些小技巧

    springboot更新配置Swagger3的一些小技巧

    今天給大家分享springboot更新配置Swagger3的方法,大家需要注意Swagger3版本需要引入依賴,具體示例代碼參考下本文
    2021-07-07
  • PowerJob的HashedWheelTimer工作流程源碼解讀

    PowerJob的HashedWheelTimer工作流程源碼解讀

    這篇文章主要為大家介紹了PowerJob的HashedWheelTimer工作流程源碼解讀,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2024-01-01
  • Idea實現(xiàn)接口的方法上無法添加@Override注解的解決方案

    Idea實現(xiàn)接口的方法上無法添加@Override注解的解決方案

    文章介紹了在IDEA中實現(xiàn)接口方法時無法添加@Override注解的問題及其解決方法,主要步驟包括更改項目結(jié)構(gòu)中的Language level到支持該注解的版本,以及在pom.xml文件中指定maven-compiler-plugin的版本以解決自動更新后的問題
    2025-02-02
  • mybatis 為什么千萬不要使用 where 1=1

    mybatis 為什么千萬不要使用 where 1=1

    這篇文章主要介紹了mybatis 為什么千萬不要使用 where 1=1,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2021-05-05
  • 淺析Java中的內(nèi)存泄漏

    淺析Java中的內(nèi)存泄漏

    這篇文章主要介紹了Java中的內(nèi)存泄漏,包括其基本概念和基本的預(yù)防措施,需要的朋友可以參考下
    2015-07-07
  • Java實現(xiàn)根據(jù)模板自動生成新的PPT

    Java實現(xiàn)根據(jù)模板自動生成新的PPT

    這篇文章主要介紹了如何利用Java代碼自動生成PPT,具體就是查詢數(shù)據(jù)庫數(shù)據(jù),然后根據(jù)模板文件(PPT),將數(shù)據(jù)庫數(shù)據(jù)與模板文件(PPT),進(jìn)行組合一下,生成新的PPT文件。感興趣的可以了解一下
    2022-02-02
  • 關(guān)于java命令的本質(zhì)邏輯揭秘過程

    關(guān)于java命令的本質(zhì)邏輯揭秘過程

    Java是通過java虛擬機來裝載和執(zhí)行編譯文件(class文件)的,java虛擬機通過命令java  option 來啟動,這篇文章主要給大家介紹了關(guān)于java命令的本質(zhì)邏輯揭秘的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),需要的朋友可以參考下
    2021-05-05
  • nacos配置在代碼中引用的方法講解

    nacos配置在代碼中引用的方法講解

    這篇文章主要介紹了nacos配置在代碼中如何引用,如果主配置中配置的內(nèi)容和拓展配置的內(nèi)容重復(fù)則按主配置的配置 ,如果拓展配置中的內(nèi)容和另一個拓展配置中的內(nèi)容重復(fù),則按下標(biāo)大的配置作為最終的配置,對nacos配置代碼引用相關(guān)知識感興趣朋友一起看看吧
    2022-12-12
  • java中常見的中文亂碼總結(jié)

    java中常見的中文亂碼總結(jié)

    本文主要介紹了java中常見的中文亂碼以及解決方法,主要包括字節(jié)碼文件讀取時出現(xiàn)的亂碼問題,本文通過實例代碼給大家介紹的非常詳細(xì),具有很好的參考價值,感興趣的朋友跟隨小編一起看看吧
    2017-03-03

最新評論

三门县| 武宣县| 万盛区| 盈江县| 缙云县| 固安县| 故城县| 鹤庆县| 夏津县| 河西区| 大理市| 沁阳市| 郓城县| 登封市| 时尚| 江津市| 武义县| 嵊泗县| 山阳县| 临夏市| 砚山县| 湛江市| 景德镇市| 祁阳县| 孟村| 崇义县| 略阳县| 涟水县| 文山县| 馆陶县| 庆元县| 耒阳市| 鄂托克旗| 麻城市| 黄骅市| 安宁市| 新平| 普安县| 乌恰县| 衡阳市| 苍梧县|