Spring 源码分析(四) ——MVC(五)初始化阶段

from:https://my.oschina.net/kaywu123/blog/651838

DispatcherServlet 的初始化

        Spring MVC 是基于 Servlet 功能实现的,通过实现 Servlet 接口的 DispatcherServlet 来封装其核心功能实现,通过将请求分派给处理程序,同时带有可配置的处理程序映射、视图解析、本地语言、主题解析以及上载文件支持。下面是 DispatcherServlet 的继承图:

        servlet 初始化阶段会调用其 init 方法,所以我们首先要查看在 DispatcherServlet 中是否重写了 init 方法。我们在其父类 HttpServletBean 中找到了该方法。

HttpServletBean.java

public final void init() throws ServletException {
   if (logger.isDebugEnabled()) {
      logger.debug("Initializing servlet '" + getServletName() + "'");
   }

   // Set bean properties from init parameters.
   try {
      // 解析 init-param 并封装只 pvs 中
      PropertyValues pvs = new ServletConfigPropertyValues(getServletConfig(), this.requiredProperties);
      // 将当前的这个 Servlet 类转化为一个 BeanWrapper,从而能够以 Spring 的方法来对 init-param 的值进行注入
      BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(this);
      ResourceLoader resourceLoader = new ServletContextResourceLoader(getServletContext());
      // 注册自定义属性编辑器,一旦遇到 Resource 类型的属性将会使用 ResourceEditor 进行解析
      bw.registerCustomEditor(Resource.class, new ResourceEditor(resourceLoader, getEnvironment()));
      // 空实现,留给子类覆盖
      initBeanWrapper(bw);
      // 属性注入
      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.
   initServletBean();

   if (logger.isDebugEnabled()) {
      logger.debug("Servlet '" + getServletName() + "' configured successfully");
   }
}

        初始化的主要过程时序图如下:

        DipatcherServlet 的初始化过程主要是通过将当前的 servlet 类型实例转换为 BeanWrapper 类型实例,以便使用 Spring 中提供的注入功能进行对应属性的注入。这些属性如 contextAttribute、contextClass、nameSpace、contextConfigLocation 等,都可以在 web.xml 文件中以初始化参数的方式配置在 servlet 的声明中。DispatcherServlet 继承自 FrameworkServlet,FrameworkServlet 类上包含对应的同名属性,Spring 会保证这些参数被注入到对应的值中。属性注入主要包含以下几个步骤:

        1.封装及验证初始化参数

            ServletConfigPropertyValues 除了封装属性外还有对属性验证的功能。

HttpServletBean.java

public ServletConfigPropertyValues(ServletConfig config, Set<String> requiredProperties)
   throws ServletException {

   Set<String> missingProps = (requiredProperties != null && !requiredProperties.isEmpty()) ?
         new HashSet<String>(requiredProperties) : null;

   Enumeration<String> en = config.getInitParameterNames();
   while (en.hasMoreElements()) {
      String property = en.nextElement();
      Object value = config.getInitParameter(property);
      addPropertyValue(new PropertyValue(property, value));
      if (missingProps != null) {
         missingProps.remove(property);
      }
   }

   // Fail if we are still missing properties.
   if (missingProps != null && missingProps.size() > 0) {
      throw new ServletException(
         "Initialization from ServletConfig for servlet '" + config.getServletName() +
         "' failed; the following required properties were missing: " +
         StringUtils.collectionToDelimitedString(missingProps, ", "));
   }
}

        从代码中得知,封装属性主要是对初始化的参数进行封装,也就是 servlet 中配置的 <init-param> 中配置的封装。当然,用户可以通过对 requiredProperties 参数的初始化来强制验证某些属性的必然性,这样,在属性封装的过程中,一旦检测到 requiredProperties 中的属性没有指定初始值,就会抛出异常。

        2.将当前 servlet 实例转化成 BeanWrapper 实例

            PropertyAccessorFactory.forBeanPropertyAccess 是Spring 中提供的工具方法,主要用于将指定实例转化为 Spring 中可以处理的 BeanWrapper 类型的实例。

        3.注册相对于 Resource 的属性编辑器

            属性编辑器,我们在上文中已经介绍并且分析过其原理,这里使用属性编辑器的目的是在对当前实例(DispatcherServlet)属性注入过程中一旦遇到 Resource 类型的属性就会使用 ResourceEditor 去解析。

        4.属性注入

            BeanWrapper 为 Spring 中的方法,支持 Spring 的自动注入。其实我们最常用的属性注入无非是 contextAttribute、contextClass、nameSpace、contextConfigLocation 等属性。

        5.servletBean 的初始化

            在 ContextLoaderListener 加载的时候已经创建了 WebApplicationContext 实例,而在这个函数中最重要的就是对这个实例进行进一步的补充初始化。

            继续查看 initServletBean()。父类 FrameworkServlet 覆盖了 HttpServletBean 中的 initServletBean 函数,如下:

FrameworkServlet.java

@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");
   }
}

        上面的函数设计了计时器来统计初始化的执行时间,而且提供了一个扩展方法 initFrameworkServlet() 用于子类的覆盖操作,而作为关键的初始化逻辑实现委托给了 initWebApplicationContext();

WebApplicationContext 的初始化

        initWebApplicationContext 函数

        initWebApplicationContext 函数的主要工作就是创建或刷新 WebApplicationContext 实例并对 servlet 功能所使用的组件进行初始化。

FrameworkServlet.java

protected WebApplicationContext initWebApplicationContext() {
   WebApplicationContext rootContext =
         WebApplicationContextUtils.getWebApplicationContext(getServletContext());
   WebApplicationContext wac = null;

   if (this.webApplicationContext != null) {
      // A context instance was injected at construction time -> use it
      // context 实例在构造函数中被注入
      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
               cwac.setParent(rootContext);
            }
            // 刷新上下文环境
            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
      // 根据 contextAttribute 属性加载 WebApplicationContext
      wac = findWebApplicationContext();
   }
   if (wac == null) {
      // No context instance is defined for this servlet -> create a local one
      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(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;
}

        对于本函数中的初始化主要包含以下几个部分:

            1. 寻找或创建 WebApplicationContext 实例。

            2. WebApplicationContext 的配置。

            3. WebApplicationContext 的刷新。

        寻找或创建 WebApplicationContext 实例

        WebApplicationContext 的寻找及创建包括以下几个步骤。

        (1)通过构造函数的注入进行初始化。

        当进入 initWebApplicationContext 函数后通过判断 this.webApplicationContext != null 后,便可以确定 this.webApplicationContext 是否是通过构造函数来初始化的。可是有读者可能会有疑问,在 initServletBean 函数中明明是把创建好的实例记录在了 this.webApplicationContext 中:

this.webApplicationContext = initWebApplicationContext();

        何以判定这个参数是通过构造函数初始化,而不是通过上一次的函数返回值初始化呢?如果存在这个问题,那么就是读者忽略一个问题了:在 Web 中包含 SpringWeb 的核心逻辑的 DispatcherServlet 只可以被声明为一次,在 Spring 中已经存在验证,所以这就确保了如果 this.webApplicationContext != null,则可以直接判定 this.webApplicationContext 已经通过构造函数初始化。

        (2)通过 contextAttribute 进行初始化

        通过在 web.xml 文件中配置的 servlet 参数 contextAttribute 来查找 ServletContext 中对应的属性,默认为 WebApplicationContext.class.getName() + ".ROOT",也就是在 ContextLoaderListener 加载时会创建 WebApplicationContext 实例,并将实例以 WebApplicationContext.class.getName() + ".ROOT" 为 key 放入 ServletContext 中,当然读者可以重写初始化逻辑使用自己创建的 WebApplicationContext,并在 servlet 的配置中通过初始化参数 contextAttribute 指定 key。

FrameworkServlet.java

protected WebApplicationContext findWebApplicationContext() {
   String attrName = getContextAttribute();
   if (attrName == null) {
      return null;
   }
   WebApplicationContext wac =
         WebApplicationContextUtils.getWebApplicationContext(getServletContext(), attrName);
   if (wac == null) {
      throw new IllegalStateException("No WebApplicationContext found: initializer not registered?");
   }
   return wac;
}

        (3)重新创建 WebApplicationContext 实例。

        如果通过以上两种方式并没有找到任何突破,那就没办法了,只能在这里重新创建新的实例了。

FrameworkServlet.java

protected WebApplicationContext createWebApplicationContext(WebApplicationContext parent) {
   return createWebApplicationContext((ApplicationContext) parent);
}

protected WebApplicationContext createWebApplicationContext(ApplicationContext parent) {
   // 获取 servlet 的初始化参数 contextClass,如果没有配置默认为 XMLWebApplicationContext.Class
   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");
   }
   // 通过反射方式实例化 contextClass
   ConfigurableWebApplicationContext wac =
         (ConfigurableWebApplicationContext) BeanUtils.instantiateClass(contextClass);

   // parent 为在 ContextLoaderListener 中创建的实例
   // 在 ContextLoaderListener 加载的时候初始化的 WebApplicationContext 类型实例
   wac.setEnvironment(getEnvironment());
   wac.setParent(parent);
   // 获取 contextConfigLocation 属性,配置在 servlet 初始化参数中
   wac.setConfigLocation(getContextConfigLocation());

   // 初始化 Spring 环境包括加载配置文件等
   configureAndRefreshWebApplicationContext(wac);

   return wac;
}

        WebApplicationContext 的配置

        无论是通过构造函数注入还是单独创建,都免不了会调用 configureAndRefreshWebApplicationContext 方法来对已经创建的 WebApplicationContext 实例进行配置及刷新,那么这个步骤又做哪些工作呢?

FrameworkServlet.java

protected void configureAndRefreshWebApplicationContext(ConfigurableWebApplicationContext wac) {
   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
      if (this.contextId != null) {
         wac.setId(this.contextId);
      }
      else {
         // Generate default id...
         wac.setId(ConfigurableWebApplicationContext.APPLICATION_CONTEXT_ID_PREFIX +
               ObjectUtils.getDisplayString(getServletContext().getContextPath()) + "/" + getServletName());
      }
   }

   wac.setServletContext(getServletContext());
   wac.setServletConfig(getServletConfig());
   wac.setNamespace(getNamespace());
   wac.addApplicationListener(new SourceFilteringListener(wac, new ContextRefreshListener()));

   // 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(getServletContext(), getServletConfig());
   }

   postProcessWebApplicationContext(wac);
   applyInitializers(wac);
   // 加载配置文件及整合 parent 到 wac
   wac.refresh();
}

        无论调用方式如何变化,只要是使用 AlicationContext 所提供的功能最后都免不了使用公共父类 AbstractApplicationContext 提供的 refresh() 进行配置文件加载。

 

        WebApplicationContext 的刷新

        onRefresh 是 FrameworkServlet 类中提供的模板方法,在其子类 DispatcherServlet 中进行了重写,主要用于刷新 Spring 在 Web 功能实现中所必须使用的组件。下面我们会介绍它们的初始化过程以及使用场景,而至于具体的使用细节会在稍后的章节中再做详细介绍。

DispatcherServlet.java

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

protected void initStrategies(ApplicationContext context) {
   // 1.初始化 MultipartResolver
   initMultipartResolver(context);
   // 2.初始化 LocaleResolver
   initLocaleResolver(context);
   // 3.初始化 ThemeResolver
   initThemeResolver(context);
   // 4.初始化 HandlerMappings
   initHandlerMappings(context);
   // 5.初始化 HandlerAdapters
   initHandlerAdapters(context);
   // 6.初始化 HandlerExceptionResolvers
   initHandlerExceptionResolvers(context);
   // 7.初始化 RequestToViewNameTranslator
   initRequestToViewNameTranslator(context);
   // 8.初始化 ViewResolvers
   initViewResolvers(context);
   // 9.初始化 FlashMapManager
   initFlashMapManager(context);
}

        initStrategies 的具体内容非常简单,就是初始化的 9 个组件。 

HandlerMapping 的初始化

        对于具体的初始化过程,根据上面的方法名称,很容易理解。以 HandlerMapping 为例来说明这个 initHandlerMappings() 过程。这里的 Mapping 关系的作用是,为 HTTP 请求找到相应的 Controller 控制器,从而利用这些控制器 Controller 去完成设计好的数据处理工作。HandlerMappings 完成对 MVC 中 Controller 的定义和配置,只不过在 Web 这个特定的应用环境中,这些控制器是与具体的 HTTP 请求相对应的。DispatcherServlet 中 HandlerMappings 初始化过程的具体实现。在 HandlerMapping 初始化的过程中,把在 Bean 配置文件中配置好的 handlerMapping 从 Ioc 容器中取得。

private void initHandlerMappings(ApplicationContext context) {
   this.handlerMappings = null;

   // 这里导入所有的 HandlerMapping Bean,这些 Bean 可以在当前的 DispatcherServlet 的
   // Ioc 容器中,也可能在其双亲上下文中
   // 这个 detectAllHandlerMappings 的默认值设为 true,即默认地从所有的 Ioc 容器中取
   if (this.detectAllHandlerMappings) {
      // Find all HandlerMappings in the ApplicationContext, including ancestor contexts.
      Map<String, HandlerMapping> matchingBeans =
            BeanFactoryUtils.beansOfTypeIncludingAncestors(context, HandlerMapping.class, true, false);
      if (!matchingBeans.isEmpty()) {
         this.handlerMappings = new ArrayList<HandlerMapping>(matchingBeans.values());
         // We keep HandlerMappings in sorted order.
         AnnotationAwareOrderComparator.sort(this.handlerMappings);
      }
   }
   else {
      // 可以根据名称从当前的 Ioc 容器中通过 getBean 获取 handlerMapping
      try {
         HandlerMapping hm = context.getBean(HANDLER_MAPPING_BEAN_NAME, HandlerMapping.class);
         this.handlerMappings = Collections.singletonList(hm);
      }
      catch (NoSuchBeanDefinitionException ex) {
         // Ignore, we'll add a default HandlerMapping later.
      }
   }

   // Ensure we have at least one HandlerMapping, by registering
   // a default HandlerMapping if no other mappings are found.
   // 如果没有找到 handerMappings,那么需要为 servlet 设定默认的 handlerMappings,这些默认
   // 值可以设置在 DispatcherServlet.properties 中
   if (this.handlerMappings == null) {
      this.handlerMappings = getDefaultStrategies(context, HandlerMapping.class);
      if (logger.isDebugEnabled()) {
         logger.debug("No HandlerMappings found in servlet '" + getServletName() + "': using default");
      }
   }
}

        经过以上的读取过程,handlerMapping 变量就已经获取了在 BeanDefinition 中配置好的映射关系。其他的初始化过程和 handlerMapping 比较类似,都是自己从 Ioc 容器中读入配置,所以这里的 MVC 初始化过程是建立在 Ioc 容器已经初始化完成的基础上的。

猜你喜欢

转载自blog.csdn.net/u010142437/article/details/81746337