SpringBoot的两种启动方式原理

打印 上一主题 下一主题

主题 909|帖子 909|积分 2727

使用内置tomcat启动

配置案例

启动方式


  • IDEA中main函数启动
  • mvn springboot-run
  • java -jar XXX.jar
    使用这种方式时,为包管服务在背景运行,会使用nohup
    1. nohup java -jar -Xms128m -Xmx128m -Xss256k -XX:+PrintGCDetails -XX:+PrintHeapAtGC -Xloggc:/data/log/web-gc.log web.jar >/data/log/web.log &
    复制代码
    使用java -jar默认情况下,不会启动任何嵌入式Application Server,该下令只是启动一个实行jar main的JVM历程,当spring-boot-starter-web包含嵌入式tomcat服务器依赖项时,实行java -jar则会启动Application Server
配置内置tomcat属性

关于Tomcat的属性都在 org.springframework.boot.autoconfigure.web.ServerProperties 配置类中做了界说,我们只需在application.properties配置属性做配置即可。通用的Servlet容器配置都以 server 作为前缀
  1. #配置程序端口,默认为8080
  2. server.port= 8080
  3. #用户会话session过期时间,以秒为单位
  4. server.session.timeout=
  5. #配置默认访问路径,默认为/
  6. server.context-path=
复制代码
而Tomcat特有配置都以 server.tomcat 作为前缀
  1. # 配置Tomcat编码,默认为UTF-8
  2. server.tomcat.uri-encoding=UTF-8
  3. # 配置最大线程数
  4. server.tomcat.max-threads=1000
复制代码
注意:使用内置tomcat不需要有tomcat-embed-jasper和spring-boot-starter-tomcat依赖,因为在spring-boot-starter-web依赖中已经集成了tomcat
原理

从main函数说起
  1. public static ConfigurableApplicationContext run(Class<?> primarySource, String... args) {
  2.     return run(new Class[]{primarySource}, args);
  3. }
  4. // 这里run方法返回的是ConfigurableApplicationContext
  5. public static ConfigurableApplicationContext run(Class<?>[] primarySources, String[] args) {
  6.         return (new SpringApplication(primarySources)).run(args);
  7. }
复制代码
  1. public ConfigurableApplicationContext run(String... args) {
  2. ConfigurableApplicationContext context = null;
  3. Collection<SpringBootExceptionReporter> exceptionReporters = new ArrayList();
  4. this.configureHeadlessProperty();
  5. SpringApplicationRunListeners listeners = this.getRunListeners(args);
  6. listeners.starting();
  7. Collection exceptionReporters;
  8. try {
  9.   ApplicationArguments applicationArguments = new DefaultApplicationArguments(args);
  10.   ConfigurableEnvironment environment = this.prepareEnvironment(listeners, applicationArguments);
  11.   this.configureIgnoreBeanInfo(environment);
  12.   
  13.   //打印banner,这里可以自己涂鸦一下,换成自己项目的logo
  14.   Banner printedBanner = this.printBanner(environment);
  15.   
  16.   //创建应用上下文
  17.   context = this.createApplicationContext();
  18.   exceptionReporters = this.getSpringFactoriesInstances(SpringBootExceptionReporter.class, new Class[]{ConfigurableApplicationContext.class}, context);
  19.   //预处理上下文
  20.   this.prepareContext(context, environment, listeners, applicationArguments, printedBanner);
  21.   
  22.   //刷新上下文
  23.   this.refreshContext(context);
  24.   
  25.   //再刷新上下文
  26.   this.afterRefresh(context, applicationArguments);
  27.   
  28.   listeners.started(context);
  29.   this.callRunners(context, applicationArguments);
  30. } catch (Throwable var10) {
  31.   
  32. }
  33. try {
  34.   listeners.running(context);
  35.   return context;
  36. } catch (Throwable var9) {
  37.   
  38. }
  39. }
复制代码
既然我们想知道tomcat在SpringBoot中是怎么启动的,那么run方法中,重点关注创建应用上下文(createApplicationContext)和刷新上下文(refreshContext)。
创建上下文
  1. //创建上下文
  2. protected ConfigurableApplicationContext createApplicationContext() {
  3. Class<?> contextClass = this.applicationContextClass;
  4. if (contextClass == null) {
  5.   try {
  6.    switch(this.webApplicationType) {
  7.     case SERVLET:
  8.                     //创建AnnotationConfigServletWebServerApplicationContext
  9.         contextClass = Class.forName("org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext");
  10.      break;
  11.     case REACTIVE:
  12.      contextClass = Class.forName("org.springframework.boot.web.reactive.context.AnnotationConfigReactiveWebServerApplicationContext");
  13.      break;
  14.     default:
  15.      contextClass = Class.forName("org.springframework.context.annotation.AnnotationConfigApplicationContext");
  16.    }
  17.   } catch (ClassNotFoundException var3) {
  18.    throw new IllegalStateException("Unable create a default ApplicationContext, please specify an ApplicationContextClass", var3);
  19.   }
  20. }
  21. return (ConfigurableApplicationContext)BeanUtils.instantiateClass(contextClass);
  22. }
复制代码
这里会创建AnnotationConfigServletWebServerApplicationContext类。而AnnotationConfigServletWebServerApplicationContext类继承了ServletWebServerApplicationContext,而这个类是终极集成了AbstractApplicationContext。
刷新上下文
  1. //SpringApplication.java
  2. //刷新上下文
  3. private void refreshContext(ConfigurableApplicationContext context) {
  4. this.refresh(context);
  5. if (this.registerShutdownHook) {
  6.   try {
  7.    context.registerShutdownHook();
  8.   } catch (AccessControlException var3) {
  9.   }
  10. }
  11. }
  12. //这里直接调用最终父类AbstractApplicationContext.refresh()方法
  13. protected void refresh(ApplicationContext applicationContext) {
  14. ((AbstractApplicationContext)applicationContext).refresh();
  15. }
复制代码
  1. //AbstractApplicationContext.java
  2. public void refresh() throws BeansException, IllegalStateException {
  3. synchronized(this.startupShutdownMonitor) {
  4.   this.prepareRefresh();
  5.   ConfigurableListableBeanFactory beanFactory = this.obtainFreshBeanFactory();
  6.   this.prepareBeanFactory(beanFactory);
  7.   try {
  8.    this.postProcessBeanFactory(beanFactory);
  9.    this.invokeBeanFactoryPostProcessors(beanFactory);
  10.    this.registerBeanPostProcessors(beanFactory);
  11.    this.initMessageSource();
  12.    this.initApplicationEventMulticaster();
  13.    //调用各个子类的onRefresh()方法,也就说这里要回到子类:ServletWebServerApplicationContext,调用该类的onRefresh()方法
  14.    this.onRefresh();
  15.    this.registerListeners();
  16.    this.finishBeanFactoryInitialization(beanFactory);
  17.    this.finishRefresh();
  18.   } catch (BeansException var9) {
  19.    this.destroyBeans();
  20.    this.cancelRefresh(var9);
  21.    throw var9;
  22.   } finally {
  23.    this.resetCommonCaches();
  24.   }
  25. }
  26. }
复制代码
  1. //ServletWebServerApplicationContext.java
  2. //在这个方法里看到了熟悉的面孔,this.createWebServer,神秘的面纱就要揭开了。
  3. protected void onRefresh() {
  4. super.onRefresh();
  5. try {
  6.   this.createWebServer();
  7. } catch (Throwable var2) {
  8.   
  9. }
  10. }
  11. //ServletWebServerApplicationContext.java
  12. //这里是创建webServer,但是还没有启动tomcat,这里是通过ServletWebServerFactory创建,那么接着看下ServletWebServerFactory
  13. private void createWebServer() {
  14. WebServer webServer = this.webServer;
  15. ServletContext servletContext = this.getServletContext();
  16. if (webServer == null && servletContext == null) {
  17.   ServletWebServerFactory factory = this.getWebServerFactory();
  18.   this.webServer = factory.getWebServer(new ServletContextInitializer[]{this.getSelfInitializer()});
  19. } else if (servletContext != null) {
  20.   try {
  21.    this.getSelfInitializer().onStartup(servletContext);
  22.   } catch (ServletException var4) {
  23.   
  24.   }
  25. }
  26. this.initPropertySources();
  27. }
  28. //接口
  29. public interface ServletWebServerFactory {
  30.     WebServer getWebServer(ServletContextInitializer... initializers);
  31. }
  32. //实现
  33. AbstractServletWebServerFactory
  34. JettyServletWebServerFactory
  35. TomcatServletWebServerFactory
  36. UndertowServletWebServerFactory
复制代码
这里ServletWebServerFactory接口有4个实现类,对应着四种容器:
而其中我们常用的有两个:TomcatServletWebServerFactory和JettyServletWebServerFactory。
  1. //TomcatServletWebServerFactory.java
  2. //这里我们使用的tomcat,所以我们查看TomcatServletWebServerFactory。到这里总算是看到了tomcat的踪迹。
  3. @Override
  4. public WebServer getWebServer(ServletContextInitializer... initializers) {
  5. Tomcat tomcat = new Tomcat();
  6. File baseDir = (this.baseDirectory != null) ? this.baseDirectory : createTempDir("tomcat");
  7. tomcat.setBaseDir(baseDir.getAbsolutePath());
  8.     //创建Connector对象
  9. Connector connector = new Connector(this.protocol);
  10. tomcat.getService().addConnector(connector);
  11. customizeConnector(connector);
  12. tomcat.setConnector(connector);
  13. tomcat.getHost().setAutoDeploy(false);
  14. configureEngine(tomcat.getEngine());
  15. for (Connector additionalConnector : this.additionalTomcatConnectors) {
  16.   tomcat.getService().addConnector(additionalConnector);
  17. }
  18. prepareContext(tomcat.getHost(), initializers);
  19. return getTomcatWebServer(tomcat);
  20. }
  21. protected TomcatWebServer getTomcatWebServer(Tomcat tomcat) {
  22. return new TomcatWebServer(tomcat, getPort() >= 0);
  23. }
  24. //Tomcat.java
  25. //返回Engine容器,看到这里,如果熟悉tomcat源码的话,对engine不会感到陌生。
  26. public Engine getEngine() {
  27.     Service service = getServer().findServices()[0];
  28.     if (service.getContainer() != null) {
  29.         return service.getContainer();
  30.     }
  31.     Engine engine = new StandardEngine();
  32.     engine.setName( "Tomcat" );
  33.     engine.setDefaultHost(hostname);
  34.     engine.setRealm(createDefaultRealm());
  35.     service.setContainer(engine);
  36.     return engine;
  37. }
  38. //Engine是最高级别容器,Host是Engine的子容器,Context是Host的子容器,Wrapper是Context的子容器
复制代码
getWebServer这个方法创建了Tomcat对象,并且做了两件重要的事情:把Connector对象添加到tomcat中,configureEngine(tomcat.getEngine());
getWebServer方法返回的是TomcatWebServer。
  1. //TomcatWebServer.java
  2. //这里调用构造函数实例化TomcatWebServer
  3. public TomcatWebServer(Tomcat tomcat, boolean autoStart) {
  4. Assert.notNull(tomcat, "Tomcat Server must not be null");
  5. this.tomcat = tomcat;
  6. this.autoStart = autoStart;
  7. initialize();
  8. }
  9. private void initialize() throws WebServerException {
  10.     //在控制台会看到这句日志
  11. logger.info("Tomcat initialized with port(s): " + getPortsDescription(false));
  12. synchronized (this.monitor) {
  13.   try {
  14.    addInstanceIdToEngineName();
  15.    Context context = findContext();
  16.    context.addLifecycleListener((event) -> {
  17.     if (context.equals(event.getSource()) && Lifecycle.START_EVENT.equals(event.getType())) {
  18.      removeServiceConnectors();
  19.     }
  20.    });
  21.    //===启动tomcat服务===
  22.    this.tomcat.start();
  23.    rethrowDeferredStartupExceptions();
  24.    try {
  25.     ContextBindings.bindClassLoader(context, context.getNamingToken(), getClass().getClassLoader());
  26.    }
  27.    catch (NamingException ex) {
  28.                
  29.    }
  30.             
  31.             //开启阻塞非守护进程
  32.    startDaemonAwaitThread();
  33.   }
  34.   catch (Exception ex) {
  35.    stopSilently();
  36.    destroySilently();
  37.    throw new WebServerException("Unable to start embedded Tomcat", ex);
  38.   }
  39. }
  40. }
复制代码
  1. //Tomcat.java
  2. public void start() throws LifecycleException {
  3. getServer();
  4. server.start();
  5. }
  6. //这里server.start又会回到TomcatWebServer的
  7. public void stop() throws LifecycleException {
  8. getServer();
  9. server.stop();
  10. }
复制代码
  1. //TomcatWebServer.java
  2. //启动tomcat服务
  3. @Override
  4. public void start() throws WebServerException {
  5. synchronized (this.monitor) {
  6.   if (this.started) {
  7.    return;
  8.   }
  9.   try {
  10.    addPreviouslyRemovedConnectors();
  11.    Connector connector = this.tomcat.getConnector();
  12.    if (connector != null && this.autoStart) {
  13.     performDeferredLoadOnStartup();
  14.    }
  15.    checkThatConnectorsHaveStarted();
  16.    this.started = true;
  17.    //在控制台打印这句日志,如果在yml设置了上下文,这里会打印
  18.    logger.info("Tomcat started on port(s): " + getPortsDescription(true) + " with context path '"
  19.      + getContextPath() + "'");
  20.   }
  21.   catch (ConnectorStartFailedException ex) {
  22.    stopSilently();
  23.    throw ex;
  24.   }
  25.   catch (Exception ex) {
  26.    throw new WebServerException("Unable to start embedded Tomcat server", ex);
  27.   }
  28.   finally {
  29.    Context context = findContext();
  30.    ContextBindings.unbindClassLoader(context, context.getNamingToken(), getClass().getClassLoader());
  31.   }
  32. }
  33. }
  34. //关闭tomcat服务
  35. @Override
  36. public void stop() throws WebServerException {
  37. synchronized (this.monitor) {
  38.   boolean wasStarted = this.started;
  39.   try {
  40.    this.started = false;
  41.    try {
  42.     stopTomcat();
  43.     this.tomcat.destroy();
  44.    }
  45.    catch (LifecycleException ex) {
  46.    
  47.    }
  48.   }
  49.   catch (Exception ex) {
  50.    throw new WebServerException("Unable to stop embedded Tomcat", ex);
  51.   }
  52.   finally {
  53.    if (wasStarted) {
  54.     containerCounter.decrementAndGet();
  55.    }
  56.   }
  57. }
  58. }
复制代码
使用外置tomcat部署

配置案例

外置Tomcat启动SpringBoot源码点击这里
继承SpringBootServletInitializer


  • 外部容器部署的话,就不能依赖于Application的main函数了,而是要以类似于web.xml文件配置的方式来启动Spring应用上下文,此时需要在启动类中继承SpringBootServletInitializer,并重写configure方法;还添加 @SpringBootApplication 注解,这是为了能扫描到所有Spring注解的bean
方式一:启动类继承SpringBootServletInitializer实现configure:
  1. @SpringBootApplication
  2. public class SpringBootHelloWorldTomcatApplication extends SpringBootServletInitializer {
  3.         @Override
  4.     protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
  5.         return builder.sources(Application.class);
  6.     }
  7. }
复制代码
这个类的作用与在web.xml中配置负责初始化Spring应用上下文的监听器作用类似,只不过在这里不需要编写额外的XML文件了。
方式二:新增加一个类继承SpringBootServletInitializer实现configure:
  1. public class ServletInitializer extends SpringBootServletInitializer {
  2.     @Override
  3.     protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
  4.         //此处的Application.class为带有@SpringBootApplication注解的启动类
  5.         return builder.sources(Application.class);
  6.     }
  7. }
复制代码
pom.xml修改tomcat相干的配置

首先需要将 jar 变成war war
如果要将终极的打包情势改为war的话,还需要对pom.xml文件进行修改,因为spring-boot-starter-web中包含内嵌的tomcat容器,所以直接部署在外部容器会冲突报错。因此需要将内置tomcat排除
  1. <dependency>
  2.     <groupId>org.springframework.boot</groupId>
  3.     <artifactId>spring-boot-starter-web</artifactId>
  4.     <exclusions>
  5.         <exclusion>
  6.             <groupId>org.springframework.boot</groupId>
  7.             <artifactId>spring-boot-starter-tomcat</artifactId>
  8.         </exclusion>
  9.     </exclusions>
  10. </dependency>
复制代码
在这里需要移除对嵌入式Tomcat的依赖,这样打出的war包中,在lib目次下才不会包含Tomcat相干的jar包,否则将会出现启动错误。
但是移除了tomcat后,原始的sevlet也被移除了,因此还需要额外引入servet的包
  1. <dependency>
  2.       <groupId>javax.servlet</groupId>
  3.       <artifactId>javax.servlet-api</artifactId>
  4.       <version>3.0.1</version>
  5. </dependency>
复制代码
注意的题目

此时打成的包的名称应该和 application.properties 的 server.context-path=/test 保持同等
  1. <build>
  2.     <finalName>test</finalName>
  3. </build>
复制代码
如果不一样发布到tomcat的webapps下上下文会变化
原理

tomcat不会自动去启动springboot应用 ,, 所以tomcat启动的时候肯定调用了SpringBootServletInitializer的SpringApplicationBuilder , 就会启动springboot。
ServletContainerInitializer的实现放在jar包的META-INF/services文件夹下,有一个名为javax.servlet.ServletContainerInitializer的文件,内容就是ServletContainerInitializer的实现类的全类名。当servlet容器启动时候就会去该文件中找到ServletContainerInitializer的实现类,从而创建它的实例调用onstartUp。这里就是用了SPI机制
HandlesTypes(WebApplicationInitializer.class)


  • @HandlesTypes传入的类为ServletContainerInitializer感兴趣的
  • 容器会自动在classpath中找到 WebApplicationInitializer,会传入到onStartup方法的webAppInitializerClasses中
  • Set webAppInitializerClasses这里面也包括之前界说的TomcatStartSpringBoot
  1. @HandlesTypes(WebApplicationInitializer.class)
  2. public class SpringServletContainerInitializer implements ServletContainerInitializer {
复制代码
  1. @Override
  2. public void onStartup(@Nullable Set<Class<?>> webAppInitializerClasses, ServletContext servletContext)
  3.       throws ServletException {
  4.    List<WebApplicationInitializer> initializers = new LinkedList<>();
  5.    if (webAppInitializerClasses != null) {
  6.       for (Class<?> waiClass : webAppInitializerClasses) {
  7.         // 如果不是接口 不是抽象 跟WebApplicationInitializer有关系  就会实例化
  8.          if (!waiClass.isInterface() && !Modifier.isAbstract(waiClass.getModifiers()) &&
  9.                WebApplicationInitializer.class.isAssignableFrom(waiClass)) {
  10.             try {
  11.                initializers.add((WebApplicationInitializer)
  12.                      ReflectionUtils.accessibleConstructor(waiClass).newInstance());
  13.             }
  14.             catch (Throwable ex) {
  15.                throw new ServletException("Failed to instantiate WebApplicationInitializer class", ex);
  16.             }
  17.          }
  18.       }
  19.    }
  20.    if (initializers.isEmpty()) {
  21.       servletContext.log("No Spring WebApplicationInitializer types detected on classpath");
  22.       return;
  23.    }
  24.    servletContext.log(initializers.size() + " Spring WebApplicationInitializers detected on classpath");
  25.    // 排序
  26.    AnnotationAwareOrderComparator.sort(initializers);
  27.    for (WebApplicationInitializer initializer : initializers) {
  28.       initializer.onStartup(servletContext);
  29.    }
  30. }
复制代码
  1. @Override
  2. public void onStartup(ServletContext servletContext) throws ServletException {
  3.    // Logger initialization is deferred in case an ordered
  4.    // LogServletContextInitializer is being used
  5.    this.logger = LogFactory.getLog(getClass());
  6.    WebApplicationContext rootApplicationContext = createRootApplicationContext(servletContext);
  7.    if (rootApplicationContext != null) {
  8.       servletContext.addListener(new SpringBootContextLoaderListener(rootApplicationContext, servletContext));
  9.    }
  10.    else {
  11.       this.logger.debug("No ContextLoaderListener registered, as createRootApplicationContext() did not "
  12.             + "return an application context");
  13.    }
  14. }
复制代码
SpringBootServletInitializer
  1. protected WebApplicationContext createRootApplicationContext(ServletContext servletContext) {
  2.    SpringApplicationBuilder builder = createSpringApplicationBuilder();
  3.    builder.main(getClass());
  4.    ApplicationContext parent = getExistingRootWebApplicationContext(servletContext);
  5.    if (parent != null) {
  6.       this.logger.info("Root context already created (using as parent).");
  7.       servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, null);
  8.       builder.initializers(new ParentContextApplicationContextInitializer(parent));
  9.    }
  10.    builder.initializers(new ServletContextApplicationContextInitializer(servletContext));
  11.    builder.contextClass(AnnotationConfigServletWebServerApplicationContext.class);
  12.    // 调用configure
  13.    builder = configure(builder); //①
  14.    builder.listeners(new WebEnvironmentPropertySourceInitializer(servletContext));
  15.    SpringApplication application = builder.build();//②
  16.    if (application.getAllSources().isEmpty()
  17.          && MergedAnnotations.from(getClass(), SearchStrategy.TYPE_HIERARCHY).isPresent(Configuration.class)) {
  18.       application.addPrimarySources(Collections.singleton(getClass()));
  19.    }
  20.    Assert.state(!application.getAllSources().isEmpty(),
  21.          "No SpringApplication sources have been defined. Either override the "
  22.                + "configure method or add an @Configuration annotation");
  23.    // Ensure error pages are registered
  24.    if (this.registerErrorPageFilter) {
  25.       application.addPrimarySources(Collections.singleton(ErrorPageFilterConfiguration.class));
  26.    }
  27.    application.setRegisterShutdownHook(false);
  28.    return run(application);//③
  29. }
复制代码
① 当调用configure就会来到TomcatStartSpringBoot .configure,将Springboot启动类传入到builder.source
  1. @Override
  2. protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
  3.     return builder.sources(Application.class);
  4. }
复制代码
② 调用SpringApplication application = builder.build(); 就会根据传入的Springboot启动类来构建一个SpringApplication
  1. public SpringApplication build(String... args) {
  2.    configureAsChildIfNecessary(args);
  3.    this.application.addPrimarySources(this.sources);
  4.    return this.application;
  5. }
复制代码
③ 调用 return run(application); 就会启动springboot应用
  1. protected WebApplicationContext run(SpringApplication application) {
  2.    return (WebApplicationContext) application.run();
  3. }
复制代码
也就相当于Main函数启动:
  1. public static void main(String[] args) {
  2.     SpringApplication.run(Application.class, args);
  3. }
复制代码
之后的流程就与上面 使用内置Tomcat的Main函数同等了

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
回复

使用道具 举报

0 个回复

正序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

去皮卡多

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表