原文链接:http://www.studyshare.cn/blog/details/1136/1
一、SpringBoot自动拉起Tomcat
SpringBoot框架是当前比较流行的java后端开发框架,与maven结合大大简化了开发人员项目搭建的步骤,我们知道
SpringBoot的启动类启动后,tomcat容器、SpringMVC、spring事务等第三方依赖也已经自动启动。那么SpringBoot是如何启动这
些第三方依赖的呢?下面以SpringBoot拉起tomcat容器为例,进行源码分析。
java开发工具下载地址及安装教程大全,点这里。
更多技术文章,在这里。
二、源码解析之配置文件加载嵌入式Tomcat
1、进入SpringBoot启动类,@SpringBootApplication是SpringBoot扫描第三方依赖的重要注解,进入查看该注解的源码,如图(2)


2、图(2)中的重点注解是@EnableAutoConfiguration,进入该注解,如图(3)

3、图(3)中使用@Import注解对AutoConfigurationImportSelector 类进行了引入,该类做了什么事情呢?进入源码,首先调用
selectImport()方法,在该方法中调用了getAutoConfigurationEntry()方法,在之中又调用了getCandidateConfigurations()方法,
getCandidateConfigurations()方法就去META-INF/spring.factory配置文件中加载相关配置类

这个spring.factories配置文件是加载的spring-boot-autoconfigure的配置文件,由此可以推测如果自定义starter插件的话,spring也
是采用这种方式去加载的。此处不细讲自定义starter。

继续打开spring.factories配置文件,找到tomcat所在的类,tomcat加载在ServletWebServerFactoryAutoConfiguration配置类中,

进入该类,里面也通过@Import注解将EmbeddedTomcat、EmbeddedJetty、EmbeddedUndertow等嵌入式容器类加载进来了,
springboot默认是启动嵌入式tomcat容器,如果要改变启动jetty或者undertow容器,需在pom文件中去设置。如图(7)

继续进入EmbeddedTomcat类中,见图(8):

进入TomcatServletWebServerFactory类,里面的getWebServer()是关键方法,如图(9):

继续进入getTomcatWebServer()等方法,一直往下跟到tomcat初始化方法,调用tomcat.start()方法,tomcat就正式开启运行,见图(10)

走到这里tomcat在springboot中的配置以及最终启动的流程就走完了,相信大家肯定有一个疑问,图(9)中的getWebServer()
方法是在哪里调用的呢?上面的代码流程并没有发现getWebServer()被调用的地方。因为getWebServer()方法的调用根本就不在
上面的代码流程中,它是在另外一个流程中被调用的。
三、源码解析之SpringBoot调用getWebServer()
首先进入SpringBoot启动类的run方法:


进入refreshContext()方法,如图(13):

一直点击refresh()方法,如图(14):




继续进入getWebServer()方法,如图(18):


最终就调用了TomcatServletWebServerFactory类的getWebServer()方法。
总结:通过阐述一个嵌入式tomcat在SpringBoot中的启动流程,其他诸如SpringMVC等也是使用这种方式随着SpringBoot的启动而
启动的。SpringBoot是Spring的轻量级实现,不难发现,getWebServer()方法的启动是Spring源码实现。因此,也推荐多了解了解Spring的源码。