栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

浅谈Spring与SpringMVC父子容器的关系与初始化

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

浅谈Spring与SpringMVC父子容器的关系与初始化

Spring和SpringMVC的容器具有父子关系,Spring容器为父容器,SpringMVC为子容器,子容器可以引用父容器中的Bean,而父容器不可以引用子容器中的Bean。

了解了Spring与SpringMVC父子容器的关系,接下来让我们看看Spring与SpringMVC容器的初始化过程。

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

 
    contextConfigLocation//指定spring ioc配置文件的位置
    classpath*:spring
      PropertyValues pvs = new ServletConfigPropertyValues(getServletConfig(), this.requiredProperties);
     //创建BeanWrapper实例,为DispatcherServlet设置属性
      BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(this);
      ResourceLoader resourceLoader = new ServletContextResourceLoader(getServletContext());
      bw.registerCustomEditor(Resource.class, new ResourceEditor(resourceLoader, getEnvironment()));
      initBeanWrapper(bw);
     //把init-param中的参数设置到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 {
      //创建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容器进行关联
    //这就是为什么要在ServletContext中注册spring ioc容器的原因
    WebApplicationContext rootContext =
 WebApplicationContextUtils.getWebApplicationContext(getServletContext());
    //定义springMVC容器wac
    WebApplicationContext wac = null;
 
 
    //判断容器是否由编程式传入(即是否已经存在了容器实例),存在的话直接赋值给wac,给springMVC容器设置父容器
    //最后调用刷新函数configureAndRefreshWebApplicationContext(wac),作用是把springMVC的配置信息加载到容器中去(之前已经将配置信息的路径设置到了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设置为springMVC ioc的父容器
     cwac.setParent(rootContext);
   }
 
 
   configureAndRefreshWebApplicationContext(cwac);
 }
      }
    }
    if (wac == null) {
      // 在ServletContext中寻找是否有springMVC容器,初次运行是没有的,springMVC初始化完毕ServletContext就有了springMVC容器
      wac = findWebApplicationContext();
    }
 
 
    //当wac既没有没被编程式注册到容器中的,也没在ServletContext找得到,此时就要新建一个springMVC容器
    if (wac == null) {
      // 创建springMVC容器
      wac = createWebApplicationContext(rootContext);
    }
 
 
    if (!this.refreshEventReceived) {
      //到这里mvc的容器已经创建完毕,接着才是真正调用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);
    //给容器设置环境
    wac.setEnvironment(getEnvironment());
    //给容器设置父容器(就是spring容器),两个ioc容器关联在一起了
    wac.setParent(parent);
    //给容器加载springMVC的配置信息,之前已经通过bw将配置文件路径写入到了DispatcherServlet中
    wac.setConfigLocation(getContextConfigLocation());
    //上面提到过这方法,刷新容器,根据springMVC配置文件完成初始化操作,此时springMVC容器创建完成
    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);//初始化真正调用controloler方法的类
    initHandlerExceptionResolvers(context);//异常解析
    initRequestToViewNameTranslator(context);
    initViewResolvers(context);//视图解析
    initFlashMapManager(context);
  }

总结以下DispatcherServlet及各个父类(接口)的功能:

HttpServlet:实现了init方法,完成web,xml中与DispatcherServlet有关的参数的读入,初始化DispatcherServlet。

frameworkServlet:完成了springMVC ioc 容器的创建,并且将spring ioc容器设置为springMVC ioc容器的父容器,将springMVC ioc容器注册到ServletContext中

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

至此,SpringMVC容器初始化完成

以上这篇浅谈Spring与SpringMVC父子容器的关系与初始化就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持考高分网。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/132231.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号