zoukankan      html  css  js  c++  java
  • SpringBoot源码篇:深度分析SpringBoot如何省去web.xml

    一、前言

      从本博文开始,正式开启Spring及SpringBoot源码分析之旅。这可能是一个漫长的过程,因为本人之前阅读源码都是很片面的,对Spring源码没有一个系统的认识。从本文开始我会持续更新,争取在系列文章更完之后,也能让自己对Spring源码有一个系统的认识。

      在此立下一个flag,希望自己能够坚持下去。如果有幸让您能从系列文章中学到丁点的知识,还请评论,关注,或推荐。如有错误还请在评论区指出,一起讨论共同成长。

    二、SpringBoot诞生的历史背景

       随着使用 Spring 进行开发的个人和企业越来越多,Spring 也慢慢从一个单一简洁的小框架变成一个大而全的开源软件,Spring 的边界不断的进行扩充,到了后来 Spring 几乎可以做任何事情了,市面上主流的开源软件、中间件都有 Spring 对应组件支持,人们在享用 Spring 的这种便利之后,也遇到了一些问题。Spring 每集成一个开源软件,就需要增加一些基础配置,慢慢的随着人们开发的项目越来越庞大,往往需要集成很多开源软件,因此后期使用 Spirng 开发大型项目需要引入很多配置文件,太多的配置非常难以理解,并容易配置出错,到了后来人们甚至称 Spring 为配置地狱。

      Spring 似乎也意识到了这些问题,急需有这么一套软件可以解决这些问题,这个时候微服务的概念也慢慢兴起,快速开发微小独立的应用变得更为急迫,Spring 刚好处在这么一个交叉点上,于 2013 年初开始的 Spring Boot 项目的研发,2014年4月,Spring Boot 1.0.0 发布。

      Spring Boot 诞生之初,就受到开源社区的持续关注,陆续有一些个人和企业尝试着使用了 Spring Boot,并迅速喜欢上了这款开源软件。直到2016年,在国内 Spring Boot 才被正真使用了起来,期间很多研究 Spring Boot 的开发者在网上写了大量关于 Spring Boot 的文章,同时有一些公司在企业内部进行了小规模的使用,并将使用经验分享了出来。从2016年到2018年,使用 Spring Boot 的企业和个人开发者越来越多。2018年SpringBoot2.0的发布,更是将SpringBoot的热度推向了一个前所未有的高度。

    三、SpringBoot诞生的技术基础

     1、Spring的发展历史

    (1)spring1.0时代

       Spring的诞生大大促进了JAVA的发展。也降低了企业java应用开发的技术和时间成本。

    (2)spring2.0时代
      对spring1.0在繁杂的xml配置文件上做了一定的优化,让配置看起来越来越简单,但是并没语完全解决xml冗余的问题。

    (3)spring3.0时代
      可以使用spring提供的java注解来取代曾经xml配置上的问题,似乎我们曾经忘记了发生什么,spring变得前所未有的简单。Spring3.0奠定了SpringBoot自动装配的基础。3.0提供的java注解使得我们可以通过注解的方式来配置spring容器。省去了使用类似于spring-context.xml的配置文件。

      同年,Servlet3.0规范的诞生为SpringBoot彻底去掉xml(web.xml)奠定了了理论基础(对于servlet3.0来说,web.xml不再是必需品。但是Servlet3.0规范还是建议保留web.xml)。

    (4)spring4.0时代
      4.0 时代我们甚至连xml配置文件都不需要了完全使用java源码级别的配置与spring提供的注解就能快速的开发spring应用程序,但仍然无法改变Java Web应用程序的运行模式,我们仍然需要将war部署到Web Server 上,才能对外提供服务。

      4.0开始全面支持java8.0

      同年,Servlet3.1规范诞生(tomcat8开始采用Servlet3.1规范)。

      2、Servlet3.0奠定了SpringBoot 零xml配置的基础

       分析SpringBoot如何省去web.xml还得从Servlet3.0的规范说起。Servlet3.0规范规定如下(摘自穆茂强 张开涛翻译的Servlet3.1规范,3.0和3.1在这一点上只有一些细节上的变换,在此不做过多介绍):

      ServletContainerInitializer类通过jar services API查找。对于每一个应用,应用启动时,由容器创建一个ServletContainerInitializer 实例。 框架提供的ServletContainerInitializer实现必须绑定在 jar 包 的META-INF/services 目录中的一个叫做 javax.servlet.ServletContainerInitializer 的文件,根据 jar services API,指定 ServletContainerInitializer 的实现。除 ServletContainerInitializer 外,我们还有一个注解@HandlesTypes。在 ServletContainerInitializer 实现上的@HandlesTypes注解用于表示感兴趣的一些类,它们可能指定了 HandlesTypes 的 value 中的注解(类型、方法或自动级别的注解),或者是其类型的超类继承/实现了这些类之一。无论是否设置了 metadata-complete,@HandlesTypes 注解将应用。当检测一个应用的类看是否它们匹配 ServletContainerInitializer 的 HandlesTypes 指定的条件时,如果应用的一个或多个可选的 JAR 包缺失,容器可能遇到类装载问题。由于容器不能决定是否这些类型的类装载失败将阻止应用正常工作,它必须忽略它们,同时也提供一个将记录它们的配置选项。如果ServletContainerInitializer 实现没有@HandlesTypes 注解,或如果没有匹配任何指定的@HandlesType,那么它会为每个应用使用 null 值的集合调用一次。这将允许 initializer 基于应用中可用的资源决定是否需要初始化 Servlet/Filter。在任何 Servlet Listener 的事件被触发之前,当应用正在启动时,ServletContainerInitializer 的 onStartup 方法将被调用。ServletContainerInitializer’s 的onStartup 得到一个类的 Set,其或者继承/实现 initializer 表示感兴趣的类,或者它是使用指定在@HandlesTypes 注解中的任意类注解的。

      这个规范如何理解呢?

      简单来说,当实现了Servlet3.0规范的容器(比如tomcat7及以上版本)启动时,通过SPI扩展机制自动扫描所有已添加的jar包下的META-INF/services/javax.servlet.ServletContainerInitializer中指定的全路径的类,并实例化该类,然后回调META-INF/services/javax.servlet.ServletContainerInitializer文件中指定的ServletContainerInitializer的实现类的onStartup方法。 如果该类存在@HandlesTypes注解,并且在@HandlesTypes注解中指定了我们感兴趣的类,所有实现了这个类的onStartup方法将会被调用。

      再直白一点来说,存在web.xml的时候,Servlet容器会根据web.xml中的配置初始化我们的jar包(也可以说web.xml是我们的jar包和Servlet联系的中介)。而在Servlet3.0容器初始化时会调用jar包META-INF/services/javax.servlet.ServletContainerInitializer中指定的类的实现(javax.servlet.ServletContainerInitializer中的实现替代了web.xml的作用,而所谓的在@HandlesTypes注解中指定的感兴趣的类,可以理解为具体实现了web.xml的功能,当然也可以有其他的用途)。

    四、从Spring源码中分析SpringBoot如何省去web.xml

    1、META-INF/services/javax.servlet.ServletContainerInitializer

    上一节中我们介绍了SpringBoot诞生的技术基础和Servlet3.0规范。这一章节,我们通过Spring源码来分析,Spring是如何实现省去web.xml的。

    如下图所示,在org.springframework:spring-web工程下,META-INF/services/javax.servlet.ServletContainerInitializer文件中,指定了将会被Servlet容器启动时回调的类。

    2、SpringServletContainerInitializer 

    查看 SpringServletContainerInitializer  类的源码,发现确实如如上文所说,实现了 ServletContainerInitializer  ,并且也在 @HandlesTypes 注解中指定了,感兴趣的类 WebApplicationInitializer 

    可以看到onStartup方法上有一大段注释,翻译一下大致意思:

    servlet 3.0+容器启动时将自动扫描类路径以查找实现Spring的webapplicationinitializer接口的所有实现,将其放进一个Set集合中,提供给 SpringServletContainerInitializer  onStartup的第一个参数(翻译结束)。

    在Servlet容器初始化的时候会调用 SpringServletContainerInitializer  的onStartup方法,继续看onStartup方法的代码逻辑,在该onStartup方法中利用逐个调用webapplicationinitializer所有实现类中的onStartup方法。

     1 @HandlesTypes(WebApplicationInitializer.class)
     2 public class SpringServletContainerInitializer implements ServletContainerInitializer {
     3 
     4     /**
     5      * Delegate the {@code ServletContext} to any {@link WebApplicationInitializer}
     6      * implementations present on the application classpath.
     7      * <p>Because this class declares @{@code HandlesTypes(WebApplicationInitializer.class)},
     8      * Servlet 3.0+ containers will automatically scan the classpath for implementations
     9      * of Spring's {@code WebApplicationInitializer} interface and provide the set of all
    10      * such types to the {@code webAppInitializerClasses} parameter of this method.
    11      * <p>If no {@code WebApplicationInitializer} implementations are found on the classpath,
    12      * this method is effectively a no-op. An INFO-level log message will be issued notifying
    13      * the user that the {@code ServletContainerInitializer} has indeed been invoked but that
    14      * no {@code WebApplicationInitializer} implementations were found.
    15      * <p>Assuming that one or more {@code WebApplicationInitializer} types are detected,
    16      * they will be instantiated (and <em>sorted</em> if the @{@link
    17      * org.springframework.core.annotation.Order @Order} annotation is present or
    18      * the {@link org.springframework.core.Ordered Ordered} interface has been
    19      * implemented). Then the {@link WebApplicationInitializer#onStartup(ServletContext)}
    20      * method will be invoked on each instance, delegating the {@code ServletContext} such
    21      * that each instance may register and configure servlets such as Spring's
    22      * {@code DispatcherServlet}, listeners such as Spring's {@code ContextLoaderListener},
    23      * or any other Servlet API componentry such as filters.
    24      * @param webAppInitializerClasses all implementations of
    25      * {@link WebApplicationInitializer} found on the application classpath
    26      * @param servletContext the servlet context to be initialized
    27      * @see WebApplicationInitializer#onStartup(ServletContext)
    28      * @see AnnotationAwareOrderComparator
    29      */
    30     @Override
    31     public void onStartup(@Nullable Set<Class<?>> webAppInitializerClasses, ServletContext servletContext)
    32             throws ServletException {
    33 
    34         List<WebApplicationInitializer> initializers = new LinkedList<>();
    35 
    36         if (webAppInitializerClasses != null) {
    37             for (Class<?> waiClass : webAppInitializerClasses) {
    38                 // Be defensive: Some servlet containers provide us with invalid classes,
    39                 // no matter what @HandlesTypes says...
    40                 if (!waiClass.isInterface() && !Modifier.isAbstract(waiClass.getModifiers()) &&
    41                         WebApplicationInitializer.class.isAssignableFrom(waiClass)) {
    42                     try {
    43                         initializers.add((WebApplicationInitializer)
    44                                 ReflectionUtils.accessibleConstructor(waiClass).newInstance());
    45                     }
    46                     catch (Throwable ex) {
    47                         throw new ServletException("Failed to instantiate WebApplicationInitializer class", ex);
    48                     }
    49                 }
    50             }
    51         }
    52 
    53         if (initializers.isEmpty()) {
    54             servletContext.log("No Spring WebApplicationInitializer types detected on classpath");
    55             return;
    56         }
    57 
    58         servletContext.log(initializers.size() + " Spring WebApplicationInitializers detected on classpath");
    59         AnnotationAwareOrderComparator.sort(initializers);
    60         for (WebApplicationInitializer initializer : initializers) {
    61             initializer.onStartup(servletContext);
    62         }
    63     }
    64 
    65 }

     3、WebApplicationInitializer 

    查看 WebApplicationInitializer  接口,这个接口也就是上文中所说的Servlet3.0规范中 @HandlesTypes(WebApplicationInitializer.class) 注解中所指定的感兴趣的类。

    截取一段很重要的注释。这段注释告诉我们实现该接口的类主要需要实现的功能就是web.xml中配置文件中配置的内容。

     1 /*
     2  * <servlet>
     3  *   <servlet-name>dispatcher</servlet-name>
     4  *   <servlet-class>
     5  *     org.springframework.web.servlet.DispatcherServlet
     6  *   </servlet-class>
     7  *   <init-param>
     8  *     <param-name>contextConfigLocation</param-name>
     9  *     <param-value>/WEB-INF/spring/dispatcher-config.xml</param-value>
    10  *   </init-param>
    11  *   <load-on-startup>1</load-on-startup>
    12  * </servlet>
    13  *
    14  * <servlet-mapping>
    15  *   <servlet-name>dispatcher</servlet-name>
    16  *   <url-pattern>/</url-pattern>
    17  * </servlet-mapping>}</pre>
    18  *
    19  */
    20 public interface WebApplicationInitializer {
    21     void onStartup(ServletContext servletContext) throws ServletException;
    22 }

    4、SpringBoot的 WebApplicationInitializer 的实现

    查看SpringBoot  SpringBootServletInitializer 源码,该类在spring-boot依赖包中。

    仔细看下面的标蓝的代码。不难发现这正是Servlet容器(tomcat)如何找到SpringBoot并启动它的。

      1 package org.springframework.boot.web.support;
      2 
      3 import javax.servlet.Filter;
      4 import javax.servlet.Servlet;
      5 import javax.servlet.ServletContext;
      6 import javax.servlet.ServletContextEvent;
      7 import javax.servlet.ServletException;
      8 
      9 import org.apache.commons.logging.Log;
     10 import org.apache.commons.logging.LogFactory;
     11 
     12 import org.springframework.boot.SpringApplication;
     13 import org.springframework.boot.builder.ParentContextApplicationContextInitializer;
     14 import org.springframework.boot.builder.SpringApplicationBuilder;
     15 import org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext;
     16 import org.springframework.boot.web.servlet.ServletContextInitializer;
     17 import org.springframework.context.ApplicationContext;
     18 import org.springframework.context.annotation.Configuration;
     19 import org.springframework.core.annotation.AnnotationUtils;
     20 import org.springframework.util.Assert;
     21 import org.springframework.web.WebApplicationInitializer;
     22 import org.springframework.web.context.ContextLoaderListener;
     23 import org.springframework.web.context.WebApplicationContext;
     24 import org.springframework.web.context.support.StandardServletEnvironment;
     25 
     26 /**
     27  * An opinionated {@link WebApplicationInitializer} to run a {@link SpringApplication}
     28  * from a traditional WAR deployment. Binds {@link Servlet}, {@link Filter} and
     29  * {@link ServletContextInitializer} beans from the application context to the servlet
     30  * container.
     31  * <p>
     32  * To configure the application either override the
     33  * {@link #configure(SpringApplicationBuilder)} method (calling
     34  * {@link SpringApplicationBuilder#sources(Object...)}) or make the initializer itself a
     35  * {@code @Configuration}. If you are using {@link SpringBootServletInitializer} in
     36  * combination with other {@link WebApplicationInitializer WebApplicationInitializers} you
     37  * might also want to add an {@code @Ordered} annotation to configure a specific startup
     38  * order.
     39  * <p>
     40  * Note that a WebApplicationInitializer is only needed if you are building a war file and
     41  * deploying it. If you prefer to run an embedded container then you won't need this at
     42  * all.
     43  *
     44  * @author Dave Syer
     45  * @author Phillip Webb
     46  * @author Andy Wilkinson
     47  * @since 1.4.0
     48  * @see #configure(SpringApplicationBuilder)
     49  */
     50 public abstract class SpringBootServletInitializer implements WebApplicationInitializer {
     51 
     52     protected Log logger; // Don't initialize early
     53 
     54     private boolean registerErrorPageFilter = true;
     55 
     56     /**
     57      * Set if the {@link ErrorPageFilter} should be registered. Set to {@code false} if
     58      * error page mappings should be handled via the Servlet container and not Spring
     59      * Boot.
     60      * @param registerErrorPageFilter if the {@link ErrorPageFilter} should be registered.
     61      */
     62     protected final void setRegisterErrorPageFilter(boolean registerErrorPageFilter) {
     63         this.registerErrorPageFilter = registerErrorPageFilter;
     64     }
     65 
     66     @Override
     67     public void onStartup(ServletContext servletContext) throws ServletException {
     68         // Logger initialization is deferred in case a ordered
     69         // LogServletContextInitializer is being used
     70         this.logger = LogFactory.getLog(getClass());
     71         WebApplicationContext rootAppContext = createRootApplicationContext(
     72                 servletContext);
     73         if (rootAppContext != null) {
     74             servletContext.addListener(new ContextLoaderListener(rootAppContext) {
     75                 @Override
     76                 public void contextInitialized(ServletContextEvent event) {
     77                     // no-op because the application context is already initialized
     78                 }
     79             });
     80         }
     81         else {
     82             this.logger.debug("No ContextLoaderListener registered, as "
     83                     + "createRootApplicationContext() did not "
     84                     + "return an application context");
     85         }
     86     }
     87 
     88     protected WebApplicationContext createRootApplicationContext(
     89             ServletContext servletContext) {
     90         SpringApplicationBuilder builder = createSpringApplicationBuilder();
     91         StandardServletEnvironment environment = new StandardServletEnvironment();
     92         environment.initPropertySources(servletContext, null);
     93         builder.environment(environment);
     94         builder.main(getClass());
     95         ApplicationContext parent = getExistingRootWebApplicationContext(servletContext);
     96         if (parent != null) {
     97             this.logger.info("Root context already created (using as parent).");
     98             servletContext.setAttribute(
     99                     WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, null);
    100             builder.initializers(new ParentContextApplicationContextInitializer(parent));
    101         }
    102         builder.initializers(
    103                 new ServletContextApplicationContextInitializer(servletContext));
    104         builder.contextClass(AnnotationConfigEmbeddedWebApplicationContext.class);
    105         builder = configure(builder);
    106         SpringApplication application = builder.build();
    107         if (application.getSources().isEmpty() && AnnotationUtils
    108                 .findAnnotation(getClass(), Configuration.class) != null) {
    109             application.getSources().add(getClass());
    110         }
    111         Assert.state(!application.getSources().isEmpty(),
    112                 "No SpringApplication sources have been defined. Either override the "
    113                         + "configure method or add an @Configuration annotation");
    114         // Ensure error pages are registered
    115         if (this.registerErrorPageFilter) {
    116             application.getSources().add(ErrorPageFilterConfiguration.class);
    117         }
    118         return run(application);
    119     }
    120 
    121     /**
    122      * Returns the {@code SpringApplicationBuilder} that is used to configure and create
    123      * the {@link SpringApplication}. The default implementation returns a new
    124      * {@code SpringApplicationBuilder} in its default state.
    125      * @return the {@code SpringApplicationBuilder}.
    126      * @since 1.3.0
    127      */
    128     protected SpringApplicationBuilder createSpringApplicationBuilder() {
    129         return new SpringApplicationBuilder();
    130     }
    131 
    132     /**
    133      * Called to run a fully configured {@link SpringApplication}.
    134      * @param application the application to run
    135      * @return the {@link WebApplicationContext}
    136      */
    137     protected WebApplicationContext run(SpringApplication application) {
    138         return (WebApplicationContext) application.run();
    139     }
    140 
    141     private ApplicationContext getExistingRootWebApplicationContext(
    142             ServletContext servletContext) {
    143         Object context = servletContext.getAttribute(
    144                 WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
    145         if (context instanceof ApplicationContext) {
    146             return (ApplicationContext) context;
    147         }
    148         return null;
    149     }
    150 
    151     /**
    152      * Configure the application. Normally all you would need to do is to add sources
    153      * (e.g. config classes) because other settings have sensible defaults. You might
    154      * choose (for instance) to add default command line arguments, or set an active
    155      * Spring profile.
    156      * @param builder a builder for the application context
    157      * @return the application builder
    158      * @see SpringApplicationBuilder
    159      */
    160     protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
    161         return builder;
    162     }
    163 
    164 }

     5、查看Spring官方文档

     查看Spring 5.0.14官方文档:https://docs.spring.io/spring/docs/5.0.14.RELEASE/spring-framework-reference/web.html#spring-web

    文档中给出在传统的springMVC中在web.xml中的配置内容

     1 <web-app>
     2     <!-- 初始化Spring上下文 -->
     3     <listener>
     4         <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
     5     </listener>
     6     <!-- 指定Spring的配置文件 -->
     7     <context-param>
     8         <param-name>contextConfigLocation</param-name>
     9         <param-value>/WEB-INF/app-context.xml</param-value>
    10     </context-param>
    11     <!-- 初始化DispatcherServlet -->
    12     <servlet>
    13         <servlet-name>app</servlet-name>
    14         <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    15         <init-param>
    16             <param-name>contextConfigLocation</param-name>
    17             <param-value></param-value>
    18         </init-param>
    19         <load-on-startup>1</load-on-startup>
    20     </servlet>
    21     <servlet-mapping>
    22         <servlet-name>app</servlet-name>
    23         <url-pattern>/app/*</url-pattern>
    24     </servlet-mapping>
    25 </web-app>

    文档中提供了一个如何使用基于java代码的方式配置Servlet容器example

     1 public class MyWebApplicationInitializer implements WebApplicationInitializer {
     2 
     3     @Override
     4     public void onStartup(ServletContext servletCxt) {
     5 
     6         // Load Spring web application configuration
     7         //通过注解的方式初始化Spring的上下文
     8         AnnotationConfigWebApplicationContext ac = new AnnotationConfigWebApplicationContext();
     9         //注册spring的配置类(替代传统项目中xml的configuration)
    10         ac.register(AppConfig.class);
    11         ac.refresh();
    12 
    13         // Create and register the DispatcherServlet
    14         //基于java代码的方式初始化DispatcherServlet
    15         DispatcherServlet servlet = new DispatcherServlet(ac);
    16         ServletRegistration.Dynamic registration = servletCxt.addServlet("app", servlet);
    17         registration.setLoadOnStartup(1);
    18         registration.addMapping("/app/*");
    19     }
    20 }

     对比官方文档给出的example,不难发现上面这段java代码就是SpringBoot省去web.xml的具体实现方法。上面  MyWebApplicationInitializer   正是 WebApplicationInitializer ( @HandlesTypes(WebApplicationInitializer.class) )  接口的实现。

    官方文档提供的 MyWebApplicationInitializer  类正是SpringBoot不依赖与web.xml的关键代码。

    SpringBoot中具体实现web.xml中配置的代码没有官方文档中的example这么简单,SpringBoot中具体初始化 DispatcherServlet 的类是 DispatcherServletAutoConfiguration 。感兴趣的话可以断点调试一下。

    五、总结

    以上章节介绍了SpringBoot诞生的历史背景,每一个新技术的诞生,都是场景驱动的。然后介绍了SpringBoot能做到不依赖web.xml的技术条件。最后通过源码分析了SpringBoot中具体的实现。

    下一篇博文将利用本文讲到的知识基于Spring springframework内置tomcat简单模拟SpringBoot的基本功能。简单说就是实现一个简易版的SpringBoot。

    本文是笔者查阅大量资料,阅读大量Spring源码总结出来的,原创不易,转载请注明出处。

    如有错误请在评论区留言指正。

     参考文献:

    https://blog.csdn.net/adingyb/article/details/80707471

    https://www.jianshu.com/p/c6f4df3d720c

    小小的码农,大大的梦想
  • 相关阅读:
    画图(三,进阶之绘制表盘)
    浅谈 Fork/Join
    VS中卸载Visual Assist X
    VS中显示行号
    zabbix server安装(二)
    zabbix监控的基础概念、工作原理及架构(一)
    k8s role
    如何构建 Redis 高可用架构?
    Mysqldump参数大全
    kubespray 一键安装k8s集群
  • 原文地址:https://www.cnblogs.com/hello-shf/p/10926271.html
Copyright © 2011-2022 走看看