在上一篇博文spring-boot如何得到一个tomcat实例(基于spring-boot_v1.5.14.RELEASE)中我们介绍了基于spring-boot 1.5.14版本中tomcat的实例化过程,由于2.0版本之后这个实例化过程发生了很大的改变,所以本文将以2.0.6版本为基础介绍tomcat的实例化过程。(https://docs.spring.io/spring-boot/docs/2.0.6.RELEASE/reference/htmlsingle/)
spring-boot加载tomcat的过程如下:
(1) springboot的主函数有一个注解 @SpringBootApplication,而这个注解里有一个@EnableAutoConfiguration
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@SpringBootConfiguration
@EnableAutoConfiguration //开启自动配置
@ComponentScan(excludeFilters = {
@Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),
@Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })
public @interface SpringBootApplication {
(2) 相比于1.x版本,2.x版本废弃了自动配置类EmbeddedServletContainerAutoConfiguration,而使用了ServletWebServerFactoryAutoConfiguration和EmbeddedWebServerFactoryCustomizerAutoConfiguration两个自动配置类,下面我们分别来介绍一下这两个autoConfiguration
(3) 我们先看一下比较简单的TomcatWebServerFactoryCustomizer吧
@Configuration
@ConditionalOnWebApplication
@EnableConfigurationProperties(ServerProperties.class)
public class EmbeddedWebServerFactoryCustomizerAutoConfiguration {
@Configuration
//默认使用tomcat,因此条件满足
@ConditionalOnClass({ Tomcat.class, UpgradeProtocol.class })
public static class TomcatWebServerFactoryCustomizerConfiguration {
// 实例化一个TomcatWebServerFactoryCustomizer实例bean,
//这个bean实现了WebServerFactoryCustomizer接口,
//它的customize方法负责对ConfigurableTomcatWebServerFactory进行配置
@Bean
public TomcatWebServerFactoryCustomizer tomcatWebServerFactoryCustomizer(
Environment environment, ServerProperties serverProperties) {
return new TomcatWebServerFactoryCustomizer(environment, serverProperties);
}
}
// 由于 Server.class, Loader.class, WebAppContext.class
//默认情况下不存在,因此JettyWebServerFactoryCustomizerConfiguration不会生效
@Configuration
@ConditionalOnClass({ Server.class, Loader.class, WebAppContext.class })
public static class JettyWebServerFactoryCustomizerConfiguration {
@Bean
public JettyWebServerFactoryCustomizer jettyWebServerFactoryCustomizer(
Environment environment, ServerProperties serverProperties) {
return new JettyWebServerFactoryCustomizer(environment, serverProperties);
}
}
// 由于Undertow.class, SslClientAuthMode.class默认情况下不