SpringBoot启动tomcat
SpringApplication
构造器初始化时会选择webApplicationType在run方法里面获取具体的appplicationContext
ApplicationContext,
SpringBoot 初始化功能
- SpringApplication.run()方法解析
SpringApplication.run()
public ConfigurableApplicationContext run(String... args) {
// .. 省略前边代码
// 创建ApplicationContext
context = createApplicationContext();
// .. 省略后边代码
}
protected ConfigurableApplicationContext createApplicationContext() {
Class<?> contextClass = this.applicationContextClass;
if (contextClass == null) {
try {
switch (this.webApplicationType) {
case SERVLET:
contextClass = Class.forName(DEFAULT_WEB_CONTEXT_CLASS);
break;
case REACTIVE:
contextClass = Class.forName(DEFAULT_REACTIVE_WEB_CONTEXT_CLASS);
break;
default:
contextClass = Class.forName(DEFAULT_CONTEXT_CLASS);
}
}
catch (ClassNotFoundException ex) {
throw new IllegalStateException(
"Unable create a default ApplicationContext, "
+ "please specify an ApplicationContextClass",
ex);
}
}
return (ConfigurableApplicationContext) BeanUtils.instantiateClass(contextClass);
}
- Spring容器启动过程后会调用onR
org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext#onRefresh
protected void onRefresh() {
super.onRefresh();
try {
createWebServer();
}
catch (Throwable ex) {
throw new ApplicationContextException("Unable to start web server", ex);
}
}
createWebServer(){
}
//ServletWebServerApplicationContext#onRefresh()>>TomcatServletWebServerFactory.getWebServer()
//>>getWebServer()>> getTomcatWebServer(tomcat)>>new TomcatWebServer()
public TomcatWebServer(Tomcat tomcat, boolean autoStart) {
Assert.notNull(tomcat, "Tomcat Server must not be null");
this.tomcat = tomcat;
this.autoStart = autoStart;
initialize();
}
private void initialize() throws WebServerException {
TomcatWebServer.logger
.info("Tomcat initialized with port(s): " + getPortsDescription(false));
synchronized (this.monitor) {
try {
// Start the server to trigger initialization listeners
this.tomcat.start();
}
catch (Exception ex) {
stopSilently();
throw new WebServerException("Unable to start embedded Tomcat", ex);
}
}
}
-
Spring会自动装配几个类
tomcatServletWebServerFactoryCustomizer;里面有注册后置处理器,后置处理器会调用
ServerFactoryCustomizer.customize()
容器默认注入了2个
ServerFactoryCustomizer
的子类分别是-
TomcatWebServerFactoryCustomizer
-
TomcatServletWebServerFactoryCustomizer
-