与spring和springboot相关的重要逻辑,如果想了解源头在哪,找refresh准没错

启动类,run

@SpringBootApplication
public class KafkaBootApplication {

public static void main(String[] args) {
SpringApplication.run(KafkaBootApplication.class, args);
}

}

springboot中内置tomcat什么时候创建的,又是什么时候启动的?_tomcat

一路run

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

springboot中内置tomcat什么时候创建的,又是什么时候启动的?_tomcat_02

public static ConfigurableApplicationContext run(Class<?>[] primarySources, String[] args) {
return new SpringApplication(primarySources).run(args);
}

springboot中内置tomcat什么时候创建的,又是什么时候启动的?_spring_03

直到refreshContext(context)

springboot中内置tomcat什么时候创建的,又是什么时候启动的?_设计模式_04springboot中内置tomcat什么时候创建的,又是什么时候启动的?_spring_05

 

private void refreshContext(ConfigurableApplicationContext context) {
if (this.registerShutdownHook) {
shutdownHook.registerApplicationContext(context);
}
refresh(context);
}

springboot中内置tomcat什么时候创建的,又是什么时候启动的?_tomcat_06

protected void refresh(ConfigurableApplicationContext applicationContext) {
applicationContext.refresh();
}

springboot中内置tomcat什么时候创建的,又是什么时候启动的?_设计模式_07

走到ServletWebServerApplicationContext#refresh()
@Override
public final void refresh() throws BeansException, IllegalStateException {
try {
super.refresh();
}
catch (RuntimeException ex) {
WebServer webServer = this.webServer;
if (webServer != null) {
webServer.stop();
}
throw ex;
}
}

springboot中内置tomcat什么时候创建的,又是什么时候启动的?_tomcat_08

其实调用还是super.refresh(),也就是AbstractApplicationContext的refresh,再调用onRefresh()

springboot中内置tomcat什么时候创建的,又是什么时候启动的?_spring_09springboot中内置tomcat什么时候创建的,又是什么时候启动的?_设计模式_10

然后又回调回了ServletWebServerApplicationContext#onRefresh()

这里涉及到一个设计模式,模板方法设计模式,父类的onRefresh()是个空方法,留给子类实现。

springboot中内置tomcat什么时候创建的,又是什么时候启动的?_tomcat_11springboot中内置tomcat什么时候创建的,又是什么时候启动的?_tomcat_12

内置的tomcat就是在createWebServer()方法中

springboot中内置tomcat什么时候创建的,又是什么时候启动的?_设计模式_13springboot中内置tomcat什么时候创建的,又是什么时候启动的?_tomcat_14

 直接显示的new了一个Tomcat()

springboot中内置tomcat什么时候创建的,又是什么时候启动的?_tomcat_15springboot中内置tomcat什么时候创建的,又是什么时候启动的?_spring_16

创建的只是一个Tomcat对象,需要返回的是 TomcatWebServer,也就是启动了的Tomcat

所以还需要启动Tomcat

springboot中内置tomcat什么时候创建的,又是什么时候启动的?_tomcat_17springboot中内置tomcat什么时候创建的,又是什么时候启动的?_spring_18​编辑

 把Tomcat当作参数传过来,实例化一个TomcatWebServer对象

springboot中内置tomcat什么时候创建的,又是什么时候启动的?_spring_19springboot中内置tomcat什么时候创建的,又是什么时候启动的?_tomcat_20​编辑

实例化过程中有个步骤叫初始化initialize()

springboot中内置tomcat什么时候创建的,又是什么时候启动的?_设计模式_21springboot中内置tomcat什么时候创建的,又是什么时候启动的?_设计模式_22​编辑 

 就是在这个初始化方法中完成了Tomcat的启动

springboot中内置tomcat什么时候创建的,又是什么时候启动的?_tomcat_23springboot中内置tomcat什么时候创建的,又是什么时候启动的?_设计模式_24

 至此,springboot内置的tomcat就创建并启动完成了