SpringBoot 默认的web容器
SpringBoot 自动配置类 ServletWebServerFactoryAutoConfiguration,使用@Improt导入三个容器的配置bean
可以发现支持的容器是tomcat,jetty,undertow。
默认使用的是tomcat。而且tomcat配置bean不需要手动加入相关start。其他两个需要手动加入相关start
SpringBoot 如何配置当前web容器
1.配置WebServerFactory
@Bean public TomcatServletWebServerFactory webServerFactory(){ TomcatServletWebServerFactory factory = new TomcatServletWebServerFactory(); factory.setPort(83); return factory; }
2.配置WebServerFactoryCustomizer,重写customize()强转相应的WebServerFactory。
@Bean public WebServerFactoryCustomizer customizer(){ WebServerFactoryCustomizer customizer = new WebServerFactoryCustomizer() { @Override public void customize(WebServerFactory factory) { TomcatServletWebServerFactory factory1 = (TomcatServletWebServerFactory)factory; factory1.setPort(82); } }; return customizer; }
SpringBoot如何切换web容器(tomcat->jetty)
1.配置WebServerFactory
@Bean public JettyServletWebServerFactory jettyServletWebServerFactory(){ JettyServletWebServerFactory factory = new JettyServletWebServerFactory(); factory.setPort(84); return factory; }
2.配置WebServerFactoryCustomizer,重写customize()强转相应的WebServerFactory。
@Bean public WebServerFactoryCustomizer customizer(){ WebServerFactoryCustomizer customizer = new WebServerFactoryCustomizer() { @Override public void customize(WebServerFactory factory) { JettyServletWebServerFactory factory1 = (JettyServletWebServerFactory)factory; factory1.setPort(82); } }; return customizer; }
这种方式的配置是交由容器进行管理,此时需要在pom文件中剔除tomatjar包
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <exclusions> <exclusion> <groupId>org.apache.tomcat.embed</groupId> <artifactId>tomcat-embed-core</artifactId> </exclusion> </exclusions> </dependency>
因为在自动配置类ServletWebServerFactoryAutoConfiguration中ServletWebServerFactoryConfiguration.EmbeddedTomcat是优先于其他两种容器导入的。如果不剔除,Spring容器还是会配置tomcatWebServer。因为有
@ConditionalOnMissingBean(value = ServletWebServerFactory.class, search = SearchStrategy.CURRENT)这个条件约束。
SpringBoot 如何自动配置web容器
在spring-boot-autoconfigure包中,在META-INF文件夹中的spring.factories文件中,有一个org.springframework.boot.autoconfigure.EnableAutoConfiguration 自动注解的变量,其中有个WebSocketServletAutoConfiguration类。这个类会被SpringBoot自动配置类找到并加载。
SpringBoot自动配置web容器原理
1.@SpringBootConfiguration注解是个组合注解。其中包含了@EnableAutoConfiguration这个注解。
2.EnableAutoConfiguration注解导入了一个实现DeferredImportSelector接口的AutoConfigurationImportSelector类。
3.Spring容器初始化前,会调用
invokeBeanFactoryPostProcessors()->invokeBeanDefinitionRegistryPostProcessors()->
BeanDefinitionRegistryPostProcessor.postProcessBeanDefinitionRegistry()
此BeanDefinitionRegistryPostProcessor为bean工厂的后置处理器。实现类为ConfigurationClassPostProcessor。
会扫描到用@Import导入的方法,并把实现DeferredImportSelector接口的对象放到一个map中,后面会执行
DeferredImportSelector.getAutoConfigurationEntry()方法。
4.DeferredImportSelector.getAutoConfigurationEntry()方法会从META-INF/spring.factories文件中找到
spring.boot.enableautoconfiguration变量数组。会把定义的变量数组值配置到到Spring容器中。其中就有个
WebServicesAutoConfiguration配置类。配置了web容器。