总在说Spring Boot内置了Tomcat,能说清楚它的原理吗?

简介: 总在说Spring Boot内置了Tomcat,能说清楚它的原理吗?

不得不说SpringBoot的开发者是在为大众程序猿谋福利,把大家都惯成了懒汉,xml不配置了,连tomcat也懒的配置了,典型的一键启动系统,那么tomcat在springboot是怎么启动的呢?

内置tomcat

开发阶段对我们来说使用内置的tomcat是非常够用了,当然也可以使用jetty。

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-web</artifactId>
  <version>2.1.6.RELEASE</version>
</dependency>

@SpringBootApplication
public class MySpringbootTomcatStarter{
    public static void main(String[] args) {
        Long time=System.currentTimeMillis();
        SpringApplication.run(MySpringbootTomcatStarter.class);
        System.out.println("===应用启动耗时:"+(System.currentTimeMillis()-time)+"===");
    }
}

这里是main函数入口,两句代码最耀眼,分别是SpringBootApplication注解和SpringApplication.run()方法。

发布生产

发布的时候,目前大多数的做法还是排除内置的tomcat,打瓦包(war)然后部署在生产的tomcat中,好吧,那打包的时候应该怎么处理?

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-web</artifactId>
   <!-- 移除嵌入式tomcat插件 -->
   <exclusions>
       <exclusion>
           <groupId>org.springframework.boot</groupId>
           <artifactId>spring-boot-starter-tomcat</artifactId>
       </exclusion>
   </exclusions>
</dependency>
<!--添加servlet-api依赖--->
<dependency>
   <groupId>javax.servlet</groupId>
   <artifactId>javax.servlet-api</artifactId>
   <version>3.1.0</version>
   <scope>provided</scope>
</dependency>

更新main函数,主要是继承SpringBootServletInitializer,并重写configure()方法。

@SpringBootApplication
publicclassMySpringbootTomcatStarterextendsSpringBootServletInitializer {
   publicstaticvoidmain(String[] args) {
       Long time=System.currentTimeMillis();
       SpringApplication.run(MySpringbootTomcatStarter.class);
       System.out.println("===应用启动耗时:"+(System.currentTimeMillis()-time)+"===");
   }

   @Override
   protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
       return builder.sources(this.getClass());
   }
}

从main函数说起

publicstatic ConfigurableApplicationContext run(Class<?> primarySource, String... args) {
   return run(new Class[]{primarySource}, args);
}

--这里run方法返回的是ConfigurableApplicationContext
publicstatic ConfigurableApplicationContext run(Class<?>[] primarySources, String[] args)
{
return (new SpringApplication(primarySources)).run(args);
}
public ConfigurableApplicationContext run(String... args) {
ConfigurableApplicationContext context = null;
Collection<SpringBootExceptionReporter> exceptionReporters = new ArrayList();
this.configureHeadlessProperty();
SpringApplicationRunListeners listeners = this.getRunListeners(args);
listeners.starting();

Collection exceptionReporters;
try {
 ApplicationArguments applicationArguments = new DefaultApplicationArguments(args);
 ConfigurableEnvironment environment = this.prepareEnvironment(listeners, applicationArguments);
 this.configureIgnoreBeanInfo(environment);

 //打印banner,这里你可以自己涂鸦一下,换成自己项目的logo
 Banner printedBanner = this.printBanner(environment);

 //创建应用上下文
 context = this.createApplicationContext();
 exceptionReporters = this.getSpringFactoriesInstances(SpringBootExceptionReporter.class, new Class[]{ConfigurableApplicationContext.class}, context);

 //预处理上下文
 this.prepareContext(context, environment, listeners, applicationArguments, printedBanner);

 //刷新上下文
 this.refreshContext(context);

 //再刷新上下文
 this.afterRefresh(context, applicationArguments);

 listeners.started(context);
 this.callRunners(context, applicationArguments);
} catch (Throwable var10) {

}

try {
 listeners.running(context);
 return context;
} catch (Throwable var9) {

}
}

既然我们想知道tomcat在SpringBoot中是怎么启动的,那么run方法中,重点关注创建应用上下文(createApplicationContext)和刷新上下文(refreshContext)。

创建上下文

//创建上下文
protected ConfigurableApplicationContext createApplicationContext() {
Class<?> contextClass = this.applicationContextClass;
if (contextClass == null) {
 try {
  switch(this.webApplicationType) {
   case SERVLET:
                   //创建AnnotationConfigServletWebServerApplicationContext
       contextClass = Class.forName("org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext");
    break;
   case REACTIVE:
    contextClass = Class.forName("org.springframework.boot.web.reactive.context.AnnotationConfigReactiveWebServerApplicationContext");
    break;
   default:
    contextClass = Class.forName("org.springframework.context.annotation.AnnotationConfigApplicationContext");
  }
 } catch (ClassNotFoundException var3) {
  thrownew IllegalStateException("Unable create a default ApplicationContext, please specify an ApplicationContextClass", var3);
 }
}

return (ConfigurableApplicationContext)BeanUtils.instantiateClass(contextClass);
}

这里会创建AnnotationConfigServletWebServerApplicationContext类。而AnnotationConfigServletWebServerApplicationContext类继承了ServletWebServerApplicationContext,而这个类是最终集成了AbstractApplicationContext。

刷新上下文

//SpringApplication.java
//刷新上下文
privatevoidrefreshContext(ConfigurableApplicationContext context) {
this.refresh(context);
if (this.registerShutdownHook) {
 try {
  context.registerShutdownHook();
 } catch (AccessControlException var3) {
 }
}
}

//这里直接调用最终父类AbstractApplicationContext.refresh()方法
protectedvoidrefresh(ApplicationContext applicationContext) {
((AbstractApplicationContext)applicationContext).refresh();
}
//AbstractApplicationContext.java
publicvoidrefresh()throws BeansException, IllegalStateException {
synchronized(this.startupShutdownMonitor) {
 this.prepareRefresh();
 ConfigurableListableBeanFactory beanFactory = this.obtainFreshBeanFactory();
 this.prepareBeanFactory(beanFactory);

 try {
  this.postProcessBeanFactory(beanFactory);
  this.invokeBeanFactoryPostProcessors(beanFactory);
  this.registerBeanPostProcessors(beanFactory);
  this.initMessageSource();
  this.initApplicationEventMulticaster();
  //调用各个子类的onRefresh()方法,也就说这里要回到子类:ServletWebServerApplicationContext,调用该类的onRefresh()方法
  this.onRefresh();
  this.registerListeners();
  this.finishBeanFactoryInitialization(beanFactory);
  this.finishRefresh();
 } catch (BeansException var9) {
  this.destroyBeans();
  this.cancelRefresh(var9);
  throw var9;
 } finally {
  this.resetCommonCaches();
 }

}
}
//ServletWebServerApplicationContext.java
//在这个方法里看到了熟悉的面孔,this.createWebServer,神秘的面纱就要揭开了。
protectedvoidonRefresh() {
super.onRefresh();
try {
 this.createWebServer();
} catch (Throwable var2) {

}
}

//ServletWebServerApplicationContext.java
//这里是创建webServer,但是还没有启动tomcat,这里是通过ServletWebServerFactory创建,那么接着看下ServletWebServerFactory
privatevoidcreateWebServer() {
WebServer webServer = this.webServer;
ServletContext servletContext = this.getServletContext();
if (webServer == null && servletContext == null) {
 ServletWebServerFactory factory = this.getWebServerFactory();
 this.webServer = factory.getWebServer(new ServletContextInitializer[]{this.getSelfInitializer()});
} elseif (servletContext != null) {
 try {
  this.getSelfInitializer().onStartup(servletContext);
 } catch (ServletException var4) {

 }
}

this.initPropertySources();
}

//接口
publicinterfaceServletWebServerFactory {
   WebServer getWebServer(ServletContextInitializer... initializers);
}

//实现
AbstractServletWebServerFactory
JettyServletWebServerFactory
TomcatServletWebServerFactory
UndertowServletWebServerFactory

这里ServletWebServerFactory接口有4个实现类image.png而其中我们常用的有两个:TomcatServletWebServerFactory和JettyServletWebServerFactory。

//TomcatServletWebServerFactory.java
//这里我们使用的tomcat,所以我们查看TomcatServletWebServerFactory。到这里总算是看到了tomcat的踪迹。
@Override
public WebServer getWebServer(ServletContextInitializer... initializers) {
Tomcat tomcat = new Tomcat();
File baseDir = (this.baseDirectory != null) ? this.baseDirectory : createTempDir("tomcat");
tomcat.setBaseDir(baseDir.getAbsolutePath());
   //创建Connector对象
Connector connector = new Connector(this.protocol);
tomcat.getService().addConnector(connector);
customizeConnector(connector);
tomcat.setConnector(connector);
tomcat.getHost().setAutoDeploy(false);
configureEngine(tomcat.getEngine());
for (Connector additionalConnector : this.additionalTomcatConnectors) {
 tomcat.getService().addConnector(additionalConnector);
}
prepareContext(tomcat.getHost(), initializers);
return getTomcatWebServer(tomcat);
}

protected TomcatWebServer getTomcatWebServer(Tomcat tomcat) {
returnnew TomcatWebServer(tomcat, getPort() >= 0);
}

//Tomcat.java
//返回Engine容器,看到这里,如果熟悉tomcat源码的话,对engine不会感到陌生。
public Engine getEngine() {
   Service service = getServer().findServices()[0];
   if (service.getContainer() != null) {
       return service.getContainer();
   }
   Engine engine = new StandardEngine();
   engine.setName( "Tomcat" );
   engine.setDefaultHost(hostname);
   engine.setRealm(createDefaultRealm());
   service.setContainer(engine);
   return engine;
}
//Engine是最高级别容器,Host是Engine的子容器,Context是Host的子容器,Wrapper是Context的子容器

getWebServer这个方法创建了Tomcat对象,并且做了两件重要的事情:把Connector对象添加到tomcat中,configureEngine(tomcat.getEngine());

getWebServer方法返回的是TomcatWebServer。

//TomcatWebServer.java
//这里调用构造函数实例化TomcatWebServer
publicTomcatWebServer(Tomcat tomcat, boolean autoStart) {
Assert.notNull(tomcat, "Tomcat Server must not be null");
this.tomcat = tomcat;
this.autoStart = autoStart;
initialize();
}

privatevoidinitialize()throws WebServerException {
   //在控制台会看到这句日志
logger.info("Tomcat initialized with port(s): " + getPortsDescription(false));
synchronized (this.monitor) {
 try {
  addInstanceIdToEngineName();

  Context context = findContext();
  context.addLifecycleListener((event) -> {
   if (context.equals(event.getSource()) && Lifecycle.START_EVENT.equals(event.getType())) {
    removeServiceConnectors();
   }
  });

  //===启动tomcat服务===
  this.tomcat.start();

  rethrowDeferredStartupExceptions();

  try {
   ContextBindings.bindClassLoader(context, context.getNamingToken(), getClass().getClassLoader());
  }
  catch (NamingException ex) {

  }

           //开启阻塞非守护进程
  startDaemonAwaitThread();
 }
 catch (Exception ex) {
  stopSilently();
  destroySilently();
  thrownew WebServerException("Unable to start embedded Tomcat", ex);
 }
}
}
//Tomcat.java
publicvoidstart()throws LifecycleException {
getServer();
server.start();
}
//这里server.start又会回到TomcatWebServer的
publicvoidstop()throws LifecycleException {
getServer();
server.stop();
}
//TomcatWebServer.java
//启动tomcat服务
@Override
publicvoidstart()throws WebServerException {
synchronized (this.monitor) {
 if (this.started) {
  return;
 }
 try {
  addPreviouslyRemovedConnectors();
  Connector connector = this.tomcat.getConnector();
  if (connector != null && this.autoStart) {
   performDeferredLoadOnStartup();
  }
  checkThatConnectorsHaveStarted();
  this.started = true;
  //在控制台打印这句日志,如果在yml设置了上下文,这里会打印
  logger.info("Tomcat started on port(s): " + getPortsDescription(true) + " with context path '"
    + getContextPath() + "'");
 }
 catch (ConnectorStartFailedException ex) {
  stopSilently();
  throw ex;
 }
 catch (Exception ex) {
  thrownew WebServerException("Unable to start embedded Tomcat server", ex);
 }
 finally {
  Context context = findContext();
  ContextBindings.unbindClassLoader(context, context.getNamingToken(), getClass().getClassLoader());
 }
}
}

//关闭tomcat服务
@Override
publicvoidstop()throws WebServerException {
synchronized (this.monitor) {
 boolean wasStarted = this.started;
 try {
  this.started = false;
  try {
   stopTomcat();
   this.tomcat.destroy();
  }
  catch (LifecycleException ex) {

  }
 }
 catch (Exception ex) {
  thrownew WebServerException("Unable to stop embedded Tomcat", ex);
 }
 finally {
  if (wasStarted) {
   containerCounter.decrementAndGet();
  }
 }
}
}

附:tomcat顶层结构图image.png

tomcat最顶层容器是Server,代表着整个服务器,一个Server包含多个Service。从上图可以看除Service主要包括多个Connector和一个Container。Connector用来处理连接相关的事情,并提供Socket到Request和Response相关转化。

Container用于封装和管理Servlet,以及处理具体的Request请求。那么上文提到的Engine>Host>Context>Wrapper容器又是怎么回事呢?我们来看下图:image.png综上所述,一个tomcat只包含一个Server,一个Server可以包含多个Service,一个Service只有一个Container,但有多个Connector,这样一个服务可以处理多个连接。

多个Connector和一个Container就形成了一个Service,有了Service就可以对外提供服务了,但是Service要提供服务又必须提供一个宿主环境,那就非Server莫属了,所以整个tomcat的声明周期都由Server控制。

总结

SpringBoot的启动主要是通过实例化SpringApplication来启动的,启动过程主要做了以下几件事情:配置属性、获取监听器,发布应用开始启动事件初、始化输入参数、配置环境,输出banner、创建上下文、预处理上下文、刷新上下文、再刷新上下文、发布应用已经启动事件、发布应用启动完成事件。

在SpringBoot中启动tomcat的工作在刷新上下这一步。而tomcat的启动主要是实例化两个组件:Connector、Container,一个tomcat实例就是一个Server,一个Server包含多个Service,也就是多个应用程序,每个Service包含多个Connector和一个Container,而一个Container下又包含多个子容器。

目录
相关文章
|
缓存 Java 开发者
【Spring】原理:Bean的作用域与生命周期
本文将围绕 Spring Bean 的作用域与生命周期展开深度剖析,系统梳理作用域的类型与应用场景、生命周期的关键阶段与扩展点,并结合实际案例揭示其底层实现原理,为开发者提供从理论到实践的完整指导。
1265 22
|
人工智能 Java 开发者
【Spring】原理解析:Spring Boot 自动配置
Spring Boot通过“约定优于配置”的设计理念,自动检测项目依赖并根据这些依赖自动装配相应的Bean,从而解放开发者从繁琐的配置工作中解脱出来,专注于业务逻辑实现。
3255 0
|
Java Spring 容器
SpringBoot自动配置的原理是什么?
Spring Boot自动配置核心在于@EnableAutoConfiguration注解,它通过@Import导入配置选择器,加载META-INF/spring.factories中定义的自动配置类。这些类根据@Conditional系列注解判断是否生效。但Spring Boot 3.0后已弃用spring.factories,改用新格式的.imports文件进行配置。
1680 0
|
XML Java 测试技术
《深入理解Spring》:IoC容器核心原理与实战
Spring IoC通过控制反转与依赖注入实现对象间的解耦,由容器统一管理Bean的生命周期与依赖关系。支持XML、注解和Java配置三种方式,结合作用域、条件化配置与循环依赖处理等机制,提升应用的可维护性与可测试性,是现代Java开发的核心基石。
|
JavaScript Java Maven
【SpringBoot(二)】带你认识Yaml配置文件类型、SpringMVC的资源访问路径 和 静态资源配置的原理!
SpringBoot专栏第二章,从本章开始正式进入SpringBoot的WEB阶段开发,本章先带你认识yaml配置文件和资源的路径配置原理,以方便在后面的文章中打下基础
832 4
|
XML Java 应用服务中间件
【SpringBoot(一)】Spring的认知、容器功能讲解与自动装配原理的入门,带你熟悉Springboot中基本的注解使用
SpringBoot专栏开篇第一章,讲述认识SpringBoot、Bean容器功能的讲解、自动装配原理的入门,还有其他常用的Springboot注解!如果想要了解SpringBoot,那么就进来看看吧!
1077 2
|
缓存 Java 应用服务中间件
Spring Boot配置优化:Tomcat+数据库+缓存+日志,全场景教程
本文详解Spring Boot十大核心配置优化技巧,涵盖Tomcat连接池、数据库连接池、Jackson时区、日志管理、缓存策略、异步线程池等关键配置,结合代码示例与通俗解释,助你轻松掌握高并发场景下的性能调优方法,适用于实际项目落地。
2227 5
|
前端开发 Java 数据库连接
SpringBoot参数校验底层原理和实操。深度历险、深度解析(图解+秒懂+史上最全)
SpringBoot参数校验底层原理和实操。深度历险、深度解析(图解+秒懂+史上最全)
SpringBoot参数校验底层原理和实操。深度历险、深度解析(图解+秒懂+史上最全)
|
Java 关系型数据库 数据库
深度剖析【Spring】事务:万字详解,彻底掌握传播机制与事务原理
在Java开发中,Spring框架通过事务管理机制,帮我们轻松实现了这种“承诺”。它不仅封装了底层复杂的事务控制逻辑(比如手动开启、提交、回滚事务),还提供了灵活的配置方式,让开发者能专注于业务逻辑,而不用纠结于事务细节。
1407 1
|
缓存 安全 Java
Spring 框架核心原理与实践解析
本文详解 Spring 框架核心知识,包括 IOC(容器管理对象)与 DI(容器注入依赖),以及通过注解(如 @Service、@Autowired)声明 Bean 和注入依赖的方式。阐述了 Bean 的线程安全(默认单例可能有安全问题,需业务避免共享状态或设为 prototype)、作用域(@Scope 注解,常用 singleton、prototype 等)及完整生命周期(实例化、依赖注入、初始化、销毁等步骤)。 解析了循环依赖的解决机制(三级缓存)、AOP 的概念(公共逻辑抽为切面)、底层动态代理(JDK 与 Cglib 的区别)及项目应用(如日志记录)。介绍了事务的实现(基于 AOP
622 0