51.SpringBoot学习笔记

外部Servlet容器启动SpringBoot应用原理

Posted by Chen Xingxu on June 20, 2020

51.SpringBoot学习笔记–外部Servlet容器启动SpringBoot应用原理

Jar 包:执行 Spring Boot 主类的 main 方法,启动 IOC 容器,创建嵌入式的 Servlet 容器。

War包:启动服务器,服务器启动 Spring Boot 应用【SpringBootServletInitializer】,启动 IOC 容器。

Servlet 3.0 规范:

8.2.4 Shared libraries / runtimes pluggability:

规则:

1、服务器启动(Web 应用启动)会创建当前 Web 应用中每一个 jar 包中的 ServletContainerInitializer 实例;

2、ServletContainerInitializer 的实现放在 jar 包的 META-INF/services 文件夹下,有一个名为javax.servlet.ServletContainerInitializer 的文件,内容就是 ServletContainerInitializer 的实现类的全类名;

3、还可以使用 @HandlesTypes,在应用启动的时候加载我们感兴趣的类。

流程:

1、启动 Tomcat;

2、org\springframework\spring-web\4.3.14.RELEASE\spring-web-4.3.14.RELEASE.jar!\META-INF\services\javax.servlet.ServletContainerInitializer:

Spring 的 Web 模块里面有这个文件:org.springframework.web.SpringServletContainerInitializer

3、SpringServletContainerInitializer 将 @HandlesTypes (WebApplicationInitializer.class) 标注的所有这个类型的类都传入到 onStartup 方法的 Set<Class<?»,为这些 WebApplicationInitializer 类型的类创建实例;

4、每一个 WebApplicationInitializer 都调用自己的 onStartup:

5、相当于我们的 SpringBootServletInitializer 的类会被创建对象,并执行 onStartup 方法;

6、SpringBootServletInitializer 实例执行 onStartup 的时候会 createRootApplicationContext (创建容器):

protected WebApplicationContext createRootApplicationContext(
      ServletContext servletContext) {
    //1、创建SpringApplicationBuilder
   SpringApplicationBuilder builder = createSpringApplicationBuilder();
   StandardServletEnvironment environment = new StandardServletEnvironment();
   environment.initPropertySources(servletContext, null);
   builder.environment(environment);
   builder.main(getClass());
   ApplicationContext parent = getExistingRootWebApplicationContext(servletContext);
   if (parent != null) {
      this.logger.info("Root context already created (using as parent).");
      servletContext.setAttribute(
            WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, null);
      builder.initializers(new ParentContextApplicationContextInitializer(parent));
   }
   builder.initializers(
         new ServletContextApplicationContextInitializer(servletContext));
   builder.contextClass(AnnotationConfigEmbeddedWebApplicationContext.class);
    
    //调用configure方法,子类重写了这个方法,将SpringBoot的主程序类传入了进来
   builder = configure(builder);
    
    //使用builder创建一个Spring应用
   SpringApplication application = builder.build();
   if (application.getSources().isEmpty() && AnnotationUtils
         .findAnnotation(getClass(), Configuration.class) != null) {
      application.getSources().add(getClass());
   }
   Assert.state(!application.getSources().isEmpty(),
         "No SpringApplication sources have been defined. Either override the "
               + "configure method or add an @Configuration annotation");
   // Ensure error pages are registered
   if (this.registerErrorPageFilter) {
      application.getSources().add(ErrorPageFilterConfiguration.class);
   }
    //启动Spring应用
   return run(application);
}

7、Spring 的应用就启动了,并且创建 IOC 容器:

public ConfigurableApplicationContext run(String... args) {
   StopWatch stopWatch = new StopWatch();
   stopWatch.start();
   ConfigurableApplicationContext context = null;
   FailureAnalyzers analyzers = null;
   configureHeadlessProperty();
   SpringApplicationRunListeners listeners = getRunListeners(args);
   listeners.starting();
   try {
      ApplicationArguments applicationArguments = new DefaultApplicationArguments(
            args);
      ConfigurableEnvironment environment = prepareEnvironment(listeners,
            applicationArguments);
      Banner printedBanner = printBanner(environment);
      context = createApplicationContext();
      analyzers = new FailureAnalyzers(context);
      prepareContext(context, environment, listeners, applicationArguments,
            printedBanner);
       
       //刷新IOC容器
      refreshContext(context);
      afterRefresh(context, applicationArguments);
      listeners.finished(context, null);
      stopWatch.stop();
      if (this.logStartupInfo) {
         new StartupInfoLogger(this.mainApplicationClass)
               .logStarted(getApplicationLog(), stopWatch);
      }
      return context;
   }
   catch (Throwable ex) {
      handleRunFailure(context, listeners, analyzers, ex);
      throw new IllegalStateException(ex);
   }
}

总结:

启动 Servlet 容器,再启动 SpringBoot 应用