周其仁:停止改革,我们将面临三大麻烦

抛开立场观点不谈,且看周小平写一句话能犯多少语病

罗马尼亚的声明:小事件隐藏着大趋势——黑暗中的风:坚持做对的事相信未来的结果

布林肯突访乌克兰,为何选择去吃麦当劳?

中国不再是美国第一大进口国,贸易战殃及纺织业? 美国进一步延长352项中国商品的关税豁免期

生成图片,分享到微信朋友圈

自由微信安卓APP发布,立即下载! | 提交文章网址
查看原文

Spring MVC 原理探秘:容器的创建过程

田小波 树哥聊编程 2022-07-30

点击关注Java技术精选”,择“置顶或者星标”

精选最新技术文章,与你一起成长


1.简介

在上一篇文章中,我向大家介绍了 Spring MVC 是如何处理 HTTP 请求的。Spring MVC 可对外提供服务时,说明其已经处于了就绪状态。再次之前,Spring MVC 需要进行一系列的初始化操作。正所谓兵马未动,粮草先行。这些操作包括创建容器,加载 DispatcherServlet 中用到的各种组件等。本篇文章就来和大家讨论一下这些初始化操作中的容器创建操作,容器的创建是其他一些初始化过程的基础。那其他的就不多说了,我们直入主题吧。

2.容器的创建过程

一般情况下,我们会在一个 Web 应用中配置两个容器。一个容器用于加载 Web 层的类,比如我们的接口 Controller、HandlerMapping、ViewResolver 等。在本文中,我们把这个容器叫做 web 容器。另一个容器用于加载业务逻辑相关的类,比如 service、dao 层的一些类。在本文中,我们把这个容器叫做业务容器。在容器初始化的过程中,业务容器会先于 web 容器进行初始化。web 容器初始化时,会将业务容器作为父容器。这样做的原因是,web 容器中的一些 bean 会依赖于业务容器中的 bean。比如我们的 controller 层接口通常会依赖 service 层的业务逻辑类。下面举个例子进行说明:

如上,我们将 dao 层的类配置在 application-dao.xml 文件中,将 service 层的类配置在 application-service.xml 文件中。然后我们将这两个配置文件通过 标签导入到 application.xml 文件中。此时,我们可以让业务容器去加载 application.xml 配置文件即可。另一方面,我们将 Web 相关的配置放在 application-web.xml 文件中,并将该文件交给 Web 容器去加载。

这里我们把配置文件进行分层,结构上看起来清晰了很多,也便于维护。这个其实和代码分层是一个道理,如果我们把所有的代码都放在同一个包下,那看起来会多难受啊。同理,我们用业务容器和 Web 容器去加载不同的类也是一种分层的体现吧。当然,如果应用比较简单,仅用 Web 容器去加载所有的类也不是不可以。

2.1 业务容器的创建过程

前面说了一些背景知识作为铺垫,那下面我们开始分析容器的创建过程吧。按照创建顺序,我们先来分析业务容器的创建过程。业务容器的创建入口是 ContextLoaderListener 的 contextInitialized 方法。顾名思义,ContextLoaderListener 是用来监听 ServletContext 加载事件的。当 ServletContext 被加载后,监听器的 contextInitialized 方法就会被 Servlet 容器调用。ContextLoaderListener Spring 框架提供的,它的配置方法如下:

  1. <web-app>

  2. <listener>

  3. <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>

  4. </listener>


  5. <context-param>

  6. <param-name>contextConfigLocation</param-name>

  7. <param-value>classpath:application.xml</param-value>

  8. </context-param>


  9. <!-- 省略其他配置 -->

  10. </web-app>

如上,ContextLoaderListener 可通过 ServletContext 获取到 contextConfigLocation 配置。这样,业务容器就可以加载 application.xml 配置文件了。那下面我们来分析一下 ContextLoaderListener 的源码吧。

  1. public class ContextLoaderListener extends ContextLoader implements ServletContextListener {


  2. // 省略部分代码


  3. @Override

  4. public void contextInitialized(ServletContextEvent event) {

  5. // 初始化 WebApplicationContext

  6. initWebApplicationContext(event.getServletContext());

  7. }

  8. }


  9. public WebApplicationContext initWebApplicationContext(ServletContext servletContext) {

  10. /*

  11. * 如果 ServletContext 中 ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE 属性值

  12. * 不为空时,表明有其他监听器设置了这个属性。Spring 认为不能替换掉别的监听器设置

  13. * 的属性值,所以这里抛出异常。

  14. */

  15. if (servletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE) != null) {

  16. throw new IllegalStateException(

  17. "Cannot initialize context because there is already a root application context present - " +

  18. "check whether you have multiple ContextLoader* definitions in your web.xml!");

  19. }


  20. Log logger = LogFactory.getLog(ContextLoader.class);

  21. servletContext.log("Initializing Spring root WebApplicationContext");

  22. if (logger.isInfoEnabled()) {...}

  23. long startTime = System.currentTimeMillis();


  24. try {

  25. if (this.context == null) {

  26. // 创建 WebApplicationContext

  27. this.context = createWebApplicationContext(servletContext);

  28. }

  29. if (this.context instanceof ConfigurableWebApplicationContext) {

  30. ConfigurableWebApplicationContext cwac = (ConfigurableWebApplicationContext) this.context;

  31. if (!cwac.isActive()) {

  32. if (cwac.getParent() == null) {

  33. /*

  34. * 加载父 ApplicationContext,一般情况下,业务容器不会有父容器,

  35. * 除非进行配置

  36. */

  37. ApplicationContext parent = loadParentContext(servletContext);

  38. cwac.setParent(parent);

  39. }

  40. // 配置并刷新 WebApplicationContext

  41. configureAndRefreshWebApplicationContext(cwac, servletContext);

  42. }

  43. }


  44. // 设置 ApplicationContext 到 servletContext 中

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


  46. ClassLoader ccl = Thread.currentThread().getContextClassLoader();

  47. if (ccl == ContextLoader.class.getClassLoader()) {

  48. currentContext = this.context;

  49. }

  50. else if (ccl != null) {

  51. currentContextPerThread.put(ccl, this.context);

  52. }


  53. if (logger.isDebugEnabled()) {...}

  54. if (logger.isInfoEnabled()) {...}


  55. return this.context;

  56. }

  57. catch (RuntimeException ex) {

  58. logger.error("Context initialization failed", ex);

  59. servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, ex);

  60. throw ex;

  61. }

  62. catch (Error err) {

  63. logger.error("Context initialization failed", err);

  64. servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, err);

  65. throw err;

  66. }

  67. }

如上,我们看一下上面的创建过程。首先 Spring 会检测 ServletContext 中 ROOTWEBAPPLICATIONCONTEXTATTRIBUTE 属性有没有被设置,若被设置过,则抛出异常。若未设置,则调用 createWebApplicationContext 方法创建容器。创建好后,再调用 configureAndRefreshWebApplicationContext 方法配置并刷新容器。最后,调用 setAttribute 方法将容器设置到 ServletContext 中。经过以上几步,整个创建流程就结束了。流程并不复杂,可简单总结为 创建容器配置并刷新容器设置容器到ServletContext。这三步流程中,最后一步就不进行分析,接下来分析一下第一步和第二步流程对应的源码。如下:

  1. protected WebApplicationContext createWebApplicationContext(ServletContext sc) {

  2. // 判断创建什么类型的容器,默认类型为 XmlWebApplicationContext

  3. Class<?> contextClass = determineContextClass(sc);

  4. if (!ConfigurableWebApplicationContext.class.isAssignableFrom(contextClass)) {

  5. throw new ApplicationContextException("Custom context class [" + contextClass.getName() +

  6. "] is not of type [" + ConfigurableWebApplicationContext.class.getName() + "]");

  7. }

  8. // 通过反射创建容器

  9. return (ConfigurableWebApplicationContext) BeanUtils.instantiateClass(contextClass);

  10. }


  11. protected Class<?> determineContextClass(ServletContext servletContext) {

  12. /*

  13. * 读取用户自定义配置,比如:

  14. * <context-param>

  15. * <param-name>contextClass</param-name>

  16. * <param-value>XXXConfigWebApplicationContext</param-value>

  17. * </context-param>

  18. */

  19. String contextClassName = servletContext.getInitParameter(CONTEXT_CLASS_PARAM);

  20. if (contextClassName != null) {

  21. try {

  22. return ClassUtils.forName(contextClassName, ClassUtils.getDefaultClassLoader());

  23. }

  24. catch (ClassNotFoundException ex) {

  25. throw new ApplicationContextException(

  26. "Failed to load custom context class [" + contextClassName + "]", ex);

  27. }

  28. }

  29. else {

  30. /*

  31. * 若无自定义配置,则获取默认的容器类型,默认类型为 XmlWebApplicationContext。

  32. * defaultStrategies 读取的配置文件为 ContextLoader.properties,

  33. * 该配置文件内容如下:

  34. * org.springframework.web.context.WebApplicationContext =

  35. * org.springframework.web.context.support.XmlWebApplicationContext

  36. */

  37. contextClassName = defaultStrategies.getProperty(WebApplicationContext.class.getName());

  38. try {

  39. return ClassUtils.forName(contextClassName, ContextLoader.class.getClassLoader());

  40. }

  41. catch (ClassNotFoundException ex) {

  42. throw new ApplicationContextException(

  43. "Failed to load default context class [" + contextClassName + "]", ex);

  44. }

  45. }

  46. }

简单说一下 createWebApplicationContext 方法的流程,该方法首先会调用 determineContextClass 判断创建什么类型的容器,默认为 XmlWebApplicationContext。然后调用 instantiateClass 方法通过反射的方式创建容器实例。instantiateClass 方法就不跟进去分析了,大家可以自己去看看,比较简单。

继续往下分析,接下来分析一下 configureAndRefreshWebApplicationContext 方法的源码。如下:

  1. protected void configureAndRefreshWebApplicationContext(ConfigurableWebApplicationContext wac, ServletContext sc) {

  2. if (ObjectUtils.identityToString(wac).equals(wac.getId())) {

  3. // 从 ServletContext 中获取用户配置的 contextId 属性

  4. String idParam = sc.getInitParameter(CONTEXT_ID_PARAM);

  5. if (idParam != null) {

  6. // 设置容器 id

  7. wac.setId(idParam);

  8. }

  9. else {

  10. // 用户未配置 contextId,则设置一个默认的容器 id

  11. wac.setId(ConfigurableWebApplicationContext.APPLICATION_CONTEXT_ID_PREFIX +

  12. ObjectUtils.getDisplayString(sc.getContextPath()));

  13. }

  14. }


  15. wac.setServletContext(sc);

  16. // 获取 contextConfigLocation 配置

  17. String configLocationParam = sc.getInitParameter(CONFIG_LOCATION_PARAM);

  18. if (configLocationParam != null) {

  19. wac.setConfigLocation(configLocationParam);

  20. }


  21. ConfigurableEnvironment env = wac.getEnvironment();

  22. if (env instanceof ConfigurableWebEnvironment) {

  23. ((ConfigurableWebEnvironment) env).initPropertySources(sc, null);

  24. }


  25. customizeContext(sc, wac);


  26. // 刷新容器

  27. wac.refresh();

  28. }

上面的源码不是很长,逻辑不是很复杂。下面简单总结 configureAndRefreshWebApplicationContext 方法主要做了事情,如下:

  • 设置容器 id

  • 获取 contextConfigLocation 配置,并设置到容器中

  • 刷新容器

到此,关于业务容器的创建过程就分析完了,下面我们继续分析 Web 容器的创建过程。

2.2 Web 容器的创建过程

前面说了业务容器的创建过程,业务容器是通过 ContextLoaderListener。那 Web 容器是通过什么创建的呢?答案是通过 DispatcherServlet。我在上一篇文章介绍 HttpServletBean 抽象类时,说过该类覆写了父类 HttpServlet 中的 init 方法。这个方法就是创建 Web 容器的入口,那下面我们就从这个方法入手。如下:

  1. // -☆- org.springframework.web.servlet.HttpServletBean

  2. public final void init() throws ServletException {

  3. if (logger.isDebugEnabled()) {...}


  4. // 获取 ServletConfig 中的配置信息

  5. PropertyValues pvs = new ServletConfigPropertyValues(getServletConfig(), this.requiredProperties);

  6. if (!pvs.isEmpty()) {

  7. try {

  8. /*

  9. * 为当前对象(比如 DispatcherServlet 对象)创建一个 BeanWrapper,

  10. * 方便读/写对象属性。

  11. */

  12. BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(this);

  13. ResourceLoader resourceLoader = new ServletContextResourceLoader(getServletContext());

  14. bw.registerCustomEditor(Resource.class, new ResourceEditor(resourceLoader, getEnvironment()));

  15. initBeanWrapper(bw);

  16. // 设置配置信息到目标对象中

  17. bw.setPropertyValues(pvs, true);

  18. }

  19. catch (BeansException ex) {

  20. if (logger.isErrorEnabled()) {...}

  21. throw ex;

  22. }

  23. }


  24. // 进行后续的初始化

  25. initServletBean();


  26. if (logger.isDebugEnabled()) {...}

  27. }


  28. protected void initServletBean() throws ServletException {

  29. }

上面的源码主要做的事情是将 ServletConfig 中的配置信息设置到 HttpServletBean 的子类对象中(比如 DispatcherServlet),我们并未从上面的源码中发现创建容器的痕迹。不过如果大家注意看源码的话,会发现 initServletBean 这个方法稍显奇怪,是个空方法。这个方法的访问级别为 protected,子类可进行覆盖。HttpServletBean 子类 FrameworkServlet 覆写了这个方法,下面我们到 FrameworkServlet 中探索一番。

  1. // -☆- org.springframework.web.servlet.FrameworkServlet

  2. protected final void initServletBean() throws ServletException {

  3. getServletContext().log("Initializing Spring FrameworkServlet '" + getServletName() + "'");

  4. if (this.logger.isInfoEnabled()) {...}

  5. long startTime = System.currentTimeMillis();


  6. try {

  7. // 初始化容器

  8. this.webApplicationContext = initWebApplicationContext();

  9. initFrameworkServlet();

  10. }

  11. catch (ServletException ex) {

  12. this.logger.error("Context initialization failed", ex);

  13. throw ex;

  14. }

  15. catch (RuntimeException ex) {

  16. this.logger.error("Context initialization failed", ex);

  17. throw ex;

  18. }


  19. if (this.logger.isInfoEnabled()) {...}

  20. }


  21. protected WebApplicationContext initWebApplicationContext() {

  22. // 从 ServletContext 中获取容器,也就是 ContextLoaderListener 创建的容器

  23. WebApplicationContext rootContext =

  24. WebApplicationContextUtils.getWebApplicationContext(getServletContext());

  25. WebApplicationContext wac = null;


  26. /*

  27. * 若下面的条件成立,则需要从外部设置 webApplicationContext。有两个途径可以设置

  28. * webApplicationContext,以 DispatcherServlet 为例:

  29. * 1. 通过 DispatcherServlet 有参构造方法传入 WebApplicationContext 对象

  30. * 2. 将 DispatcherServlet 配置到其他容器中,由其他容器通过

  31. * setApplicationContext 方法进行设置

  32. *

  33. * 途径1 可参考 AbstractDispatcherServletInitializer 中的

  34. * registerDispatcherServlet 方法源码。一般情况下,代码执行到此处,

  35. * this.webApplicationContext 为 null,大家可自行调试进行验证。

  36. */

  37. if (this.webApplicationContext != null) {

  38. wac = this.webApplicationContext;

  39. if (wac instanceof ConfigurableWebApplicationContext) {

  40. ConfigurableWebApplicationContext cwac = (ConfigurableWebApplicationContext) wac;

  41. if (!cwac.isActive()) {

  42. if (cwac.getParent() == null) {

  43. // 设置 rootContext 为父容器

  44. cwac.setParent(rootContext);

  45. }

  46. // 配置并刷新容器

  47. configureAndRefreshWebApplicationContext(cwac);

  48. }

  49. }

  50. }

  51. if (wac == null) {

  52. // 尝试从 ServletContext 中获取容器

  53. wac = findWebApplicationContext();

  54. }

  55. if (wac == null) {

  56. // 创建容器,并将 rootContext 作为父容器

  57. wac = createWebApplicationContext(rootContext);

  58. }


  59. if (!this.refreshEventReceived) {

  60. onRefresh(wac);

  61. }


  62. if (this.publishContext) {

  63. String attrName = getServletContextAttributeName();

  64. // 将创建好的容器设置到 ServletContext 中

  65. getServletContext().setAttribute(attrName, wac);

  66. if (this.logger.isDebugEnabled()) {...}

  67. }


  68. return wac;

  69. }


  70. protected WebApplicationContext createWebApplicationContext(ApplicationContext parent) {

  71. // 获取容器类型,默认为 XmlWebApplicationContext.class

  72. Class<?> contextClass = getContextClass();

  73. if (this.logger.isDebugEnabled()) {...}

  74. if (!ConfigurableWebApplicationContext.class.isAssignableFrom(contextClass)) {

  75. throw new ApplicationContextException(

  76. "Fatal initialization error in servlet with name '" + getServletName() +

  77. "': custom WebApplicationContext class [" + contextClass.getName() +

  78. "] is not of type ConfigurableWebApplicationContext");

  79. }


  80. // 通过反射实例化容器

  81. ConfigurableWebApplicationContext wac =

  82. (ConfigurableWebApplicationContext) BeanUtils.instantiateClass(contextClass);


  83. wac.setEnvironment(getEnvironment());

  84. wac.setParent(parent);

  85. wac.setConfigLocation(getContextConfigLocation());


  86. // 配置并刷新容器

  87. configureAndRefreshWebApplicationContext(wac);


  88. return wac;

  89. }


  90. protected void configureAndRefreshWebApplicationContext(ConfigurableWebApplicationContext wac) {

  91. if (ObjectUtils.identityToString(wac).equals(wac.getId())) {

  92. // 设置容器 id

  93. if (this.contextId != null) {

  94. wac.setId(this.contextId);

  95. }

  96. else {

  97. // 生成默认 id

  98. wac.setId(ConfigurableWebApplicationContext.APPLICATION_CONTEXT_ID_PREFIX +

  99. ObjectUtils.getDisplayString(getServletContext().getContextPath()) + '/' + getServletName());

  100. }

  101. }


  102. wac.setServletContext(getServletContext());

  103. wac.setServletConfig(getServletConfig());

  104. wac.setNamespace(getNamespace());

  105. wac.addApplicationListener(new SourceFilteringListener(wac, new ContextRefreshListener()));


  106. ConfigurableEnvironment env = wac.getEnvironment();

  107. if (env instanceof ConfigurableWebEnvironment) {

  108. ((ConfigurableWebEnvironment) env).initPropertySources(getServletContext(), getServletConfig());

  109. }


  110. // 后置处理,子类可以覆盖进行一些自定义操作。在 Spring MVC 未使用到,是个空方法。

  111. postProcessWebApplicationContext(wac);

  112. applyInitializers(wac);

  113. // 刷新容器

  114. wac.refresh();

  115. }

以上就是创建 Web 容器的源码,下面总结一下该容器创建的过程。如下:

  • 从 ServletContext 中获取 ContextLoaderListener 创建的容器

  • 若 this.webApplicationContext != null 条件成立,仅设置父容器和刷新容器即可

  • 尝试从 ServletContext 中获取容器,若容器不为空,则无需执行步骤4

  • 创建容器,并将 rootContext 作为父容器

  • 设置容器到 ServletContext 中

到这里,关于 Web 容器的创建过程就讲完了。总的来说,Web 容器的创建过程和业务容器的创建过程大致相同,但是差异也是有的,不能忽略。

3.总结

本篇文章对 Spring MVC 两种容器的创建过程进行了较为详细的分析,总的来说两种容器的创建过程并不是很复杂。大家在分析这两种容器的创建过程时,看的不明白的地方,可以进行调试,这对于理解代码逻辑还是很有帮助的。当然阅读 Spring MVC 部分的源码最好有 Servlet 和 Spring IOC 容器方面的知识,这些是基础,Spring MVC 就是在这些基础上构建的。

限于个人能力,文章叙述有误,还望大家指明。也请多多指教,在这里说声谢谢。好了,本篇文章就到这里了。感谢大家的阅读。



推荐阅读



公众号@Java技术精选,关注 Java 程序员的个人成长,分享最新技术资讯与技术干货。与你成长有关的,我们这里都有。


↑↑原创不易,如果喜欢请转发↑↑



文章有问题?点此查看未经处理的缓存