DispatcherServlet的初始化

431 阅读3分钟

这是我参与2022首次更文挑战的第2天,活动详情查看:2022首次更文挑战

前言

SpringMVC源码学习环境搭建 - 掘金 (juejin.cn)中我们只需要创建一个DispatcherServlet对象,然后把他绑定到tomcat上就完成了tomcat和springmvc的集成,就可以愉快的进行api编写了,接下来就是学习为什么的时间了.

在学习DispatcherServlet中处理请求的核心方法doService之前我觉得可以先了解下它的初始化流程.

更'ssm风格'的example

为了演示springmvc父子容器的概念,所以我将代码修改为传统ssm的风格.(ps:依旧使用父子容器,代码可以在aoyvx/spring-framework: Spring Framework (github.com)找到) image.png

Servlet的基本概念

所有的Servlet必须实现Servlet接口,Servlet接口中定义的对应生命周期的回调方法,在第一调用Servlet时会触发对应的init方法.

DispatcherServlet初始化流程

DispatcherServlet结构图

image.png

init调用流程

  • GenericServlet#init(ServletConfig config)被调用,将config保存起来之后继续调用GenericServlet#init()
  • HttpServletBean重写了init()方法,修改当前根据config填充当前Servlet的属性然后再调用initServletBean()方法.
  • FrameworkServlet重写initServletBean()方法,调用initWebApplicationContext()初始化webApplicationContext并调用onRefresh().
  • DispatcherServlet重写onRefresh()初始化所有需要的组件.

ApplicationContext的创建

FrameworkServlet在创建WebApplicationContext的时候会先尝试从servletContext中获取rootContext,然后再有三步判断来决定wac也就是webApplicationContext的来源:

  1. 是否已经设置了wac,如果已经设置了则使用当前context.
  2. 是否已经把wact设置到ServletContext中,如果时则查询出来并保存.(注意,这里不会判断或设置rootContext)
  3. 如果前两都没找到wac则内部创建一个wac.

下面列出初始话context的代码,内部创建Context的方法比较简单就不列出了(通过反射初始化默认的XmlWebApplicationContext,再根据前面填充的contextConfigLocation设置配置文件,同时注册一个上下文刷新事件监听).

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
      wac = this.webApplicationContext;
      if (wac instanceof ConfigurableWebApplicationContext cwac && !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
      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.
      synchronized (this.onRefreshMonitor) {
         onRefresh(wac);
      }
   }

   if (this.publishContext) {
      // Publish the context as a servlet context attribute.
      String attrName = getServletContextAttributeName();
      getServletContext().setAttribute(attrName, wac);
   }

   return wac;
}

DispatcherServlet上下文的初始化

/**
 * This implementation calls {@link #initStrategies}.
 */
@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);
}

这里一共初始化了9种组件,基本所有给springmvc提供基础能力的工具都在这里初始化了.包括从字面意思就很好理解的文件上传解释器/国际化解释器,当然与api最直接相关的就是initHandlerMappings和initHandlerAdapters了. initHandlerMappings会将所有api方法封装成handlerMapping保存起来,而initHandlerAdapters会初始化用于执行handlerMapping方法的执行器.

小记

这次大概总结了下DispatcherServlet在初始化时做了些什么,接下来就是深入九个组件的初始化策略和用途.