核心提示:准备工作 我们知道SpringBoot的自动装配的秘密在org.springframework.boot.autoconfigure包下的spring.factories文件中,而嵌入Tomcat的原理就在这个文件中加载的一个配置类:org
准备工作
我们知道SpringBoot的自动装配的秘密在
org.springframework.boot.autoconfigure包下的spring.factories文件中,而嵌入Tomcat的原理就在这个文件中加载的一个配置类:org.springframework.boot.autoconfigure.web.servlet.ServletWebServerFactoryAutoConfiguration
@Configuration@AutoCo
nfigureOrder(Ordered.HIGHEST_PRECEDENCE)@Co
nditionalOnClass(ServletRequest.class)@Co
nditionalOnWebApplication(type = Type.SERVLET)@EnableCo
nfigurationProperties(ServerProperties.class)@im
port({ ServletWebServerFactoryAutoConfiguration.BeanPostProcessorsRegistrar.class, ServletWebServerFactoryConfiguration.EmbeddedTomcat.class, ServletWebServerFactoryConfiguration.EmbeddedJetty.class, ServletWebServerFactoryConfiguration.EmbeddedUndertow.class })public class ServletWebServerFactoryAutoCo
nfiguration { @Bean public ServletWebServerFactoryCustomizer servletWebServerFactoryCustomizer( ServerProperties serverProperties) { return new ServletWebServerFactoryCustomizer(serverProperties); } @Bean @Co
nditionalOnClass(name = "org.apache.catalina.startup.Tomcat") public TomcatServletWebServerFactoryCustomizer tomcatServletWebServerFactoryCustomizer( ServerProperties serverProperties) { return new TomcatServletWebServerFactoryCustomizer(serverProperties); } public static class BeanPostProcessorsRegistrar implements im
portBeanDefinitionRegistrar, BeanFactoryAware { private Co
nfigurableListableBeanFactory beanFactory; @Override public void setBeanFactory(BeanFactory beanFactory) throws BeansException { if (beanFactory instanceof ConfigurableListableBeanFactory) { this.beanFactory = (ConfigurableListableBeanFactory) beanFactory; } } @Override public void registerBeanDefinitions(Annotatio
nme
tadata im
portingClassme
tadata, BeanDefinitio
nRegistry registry) { if (this.beanFactory == null) { return; } registerSyntheticBeanIfMissing(registry, "webServerFactoryCustomizerBeanPostProcessor", WebServerFactoryCustomizerBeanPostProcessor.class); registerSyntheticBeanIfMissing(registry, "errorPageRegistrarBeanPostProcessor", ErrorPageRegistrarBeanPostProcessor.class); } private void registerSyntheticBeanIfMissing(BeanDefinitio
nRegistry registry, String name, Class<?> beanClass) { if (ObjectUtils.isEmpty( this.beanFactory.getBeanNamesForType(beanClass, true, false))) { RootBeanDefinition beanDefinition = new RootBeanDefinition(beanClass); beanDefinition.setSynthetic(true); registry.registerBeanDefinition(name, beanDefinition); } } }}
首先看一下上方的几个注解
@AutoConfigureOrder这个注解是决定配置类的加载顺序的,当注解里的值越小越先加载,而Ordered.HIGHEST_PRECEDENCE的值是Integer.MIN_VALUE也就是说这个类肯定是最先加载的那一批 @ConditionalOnXXX在之前的文章中已经无数次提到了,就不再阐述了 @EnableConfigurationProperties开启ServerProperties类的属性值配置。而这个类里面包含的就是Web服务的配置
@Co
nfigurationProperties(prefix = "server", ignoreUnknownFields = true)public class ServerProperties { private Integer port; private InetAddress address; @NestedCo
nfigurationProperty private final ErrorProperties error = new ErrorProperties(); private Boolean useForwardHeaders; private String serverHeader; private int maxHttpHeaderSize = 0; // bytes private Duration connectionTimeout; @NestedCo
nfigurationProperty private Ssl ssl; @NestedCo
nfigurationProperty private final Compression compression = new Compression(); @NestedCo
nfigurationProperty private final Http2 http2 = new Http2(); private final Servlet servlet = new Servlet(); private final Tomcat tomcat = new Tomcat(); private final Jetty jetty = new Jetty(); private final Undertow undertow = new Undertow();}
这个类的代码太多了,这里就不一一贴出来了,我们平常在application.properties中配置的server.xxx就是这个类中属性
@import引入了4个类,看都是什么吧 BeanPostProcessorsRegistrar
public static class BeanPostProcessorsRegistrar implements im
portBeanDefinitionRegistrar, BeanFactoryAware { @Override public void registerBeanDefinitions(Annotatio
nme
tadata im
portingClassme
tadata, BeanDefinitio
nRegistry registry) { if (this.beanFactory == null) { return; } registerSyntheticBeanIfMissing(registry, "webServerFactoryCustomizerBeanPostProcessor", WebServerFactoryCustomizerBeanPostProcessor.class); registerSyntheticBeanIfMissing(registry, "errorPageRegistrarBeanPostProcessor", ErrorPageRegistrarBeanPostProcessor.class); } private void registerSyntheticBeanIfMissing(BeanDefinitio
nRegistry registry, String name, Class<?> beanClass) { if (ObjectUtils.isEmpty( this.beanFactory.getBeanNamesForType(beanClass, true, false))) { RootBeanDefinition beanDefinition = new RootBeanDefinition(beanClass); beanDefinition.setSynthetic(true); registry.registerBeanDefinition(name, beanDefinition); } } }
这个类注册了两个bean:
WebServerFactoryCustomizerBeanPostProcessor和ErrorPageRegistrarBeanPostProcessor关于这两个bean的作用稍后再详细介绍
EmbeddedTomcat
@Co
nfiguration @Co
nditionalOnClass({ Servlet.class, Tomcat.class, UpgradeProtocol.class }) @Co
nditionalOnMissingBean(value = ServletWebServerFactory.class, search = SearchStrategy.CURRENT) public static class EmbeddedTomcat { @Bean public TomcatServletWebServerFactory tomcatServletWebServerFactory() { return new TomcatServletWebServerFactory(); } }
这个类会在存在Tomcat相关jar包时添加一个
TomcatServletWebServerFactorybean
其他两个相信大家都知道怎么回事了
除了这些这个类还注入了两个类ServletWebServerFactoryCustomizer和TomcatServletWebServerFactoryCustomizer
现在前期准备工作已经做好了,看一下这个Tomcat是如何启动的吧
启动
启动入口在
ServletWebServerApplicationContext中的onRefresh方法
protected void o
nRefresh() { super.o
nRefresh(); try { createWebServer(); } catch (Throwable ex) { throw new Applicatio
nContextException("Unable to start web server", ex); } }
Tomcat的启动就在createWebServer方法里面了
private void createWebServer() { WebServer webServer = this.webServer; ServletCo
ntext servletCo
ntext = getServletCo
ntext(); //第一次访问的时候两个对象都为空 if (webServer == null && servletCo
ntext == null) { ServletWebServerFactory factory = getWebServerFactory(); this.webServer = factory.getWebServer(getSelfInitializer()); } else if (servletCo
ntext != null) { try { getSelfInitializer().o
nStartup(servletContext); } catch (ServletException ex) { throw new Applicatio
nContextException("Cannot initialize servlet context", ex); } } initPropertySources(); }
首先看一下getWebServerFactory
protected ServletWebServerFactory getWebServerFactory() { // 这里获取的beanname就是上方注册的tomcatServletWebServerFactory了 String[] beanNames = getBeanFactory() .getBeanNamesForType(ServletWebServerFactory.class); if (beanNames.length == 0) { throw new Applicatio
nContextException( "Unable to start ServletWebServerApplicatio
nContext due to missing " + "ServletWebServerFactory bean."); } if (beanNames.length > 1) { throw new Applicatio
nContextException( "Unable to start ServletWebServerApplicatio
nContext due to multiple " + "ServletWebServerFactory beans : " + StringUtils.arrayToCommaDelimitedString(beanNames)); } return getBeanFactory().getBean(beanNames[0], ServletWebServerFactory.class); }
准备环境里注册的bean现在出来一个了。注意,上方还注册了一个后置处理器
EmbeddedServletContainerCustomizerBeanPostProcessor,获取beantomcatServletWebServerFactory的时候就会执行后置处理器的postProcessBeforeInitialization方法
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException { if (bean instanceof WebServerFactory) { postProcessBeforeInitialization((WebServerFactory) bean); } return bean;}private void postProcessBeforeInitialization(WebServerFactory webServerFactory) { LambdaSafe .callbacks(WebServerFactoryCustomizer.class, getCustomizers(), webServerFactory) .withLogger(WebServerFactoryCustomizerBeanPostProcessor.class) .invoke((customizer) -> customizer.customize(webServerFactory)); } private Collection<WebServerFactoryCustomizer<?>> getCustomizers() { if (this.customizers == null) { // Look up does not include the parent co
ntext this.customizers = new ArrayList<>(getWebServerFactoryCustomizerBeans()); this.customizers.sort(AnnotationAwareOrderComparator.INSTANCE); this.customizers = Collections.unmodifiableList(this.customizers); } return this.customizers; } @SuppressWarnings({ "unchecked", "rawtypes" }) private Collection<WebServerFactoryCustomizer<?>> getWebServerFactoryCustomizerBeans() { return (Collection) this.beanFactory .getBeansOfType(WebServerFactoryCustomizer.class, false, false).values(); }
这个处理器的作用是获得所有定制器,然后执行定制器的方法
接着往下看
这个时候就可以启动Tomcat了
public WebServer getWebServer(ServletContextInitializer... initializers) { Tomcat tomcat = new Tomcat(); File ba
seDir = (this.ba
seDirectory != null ? this.ba
seDirectory : createTempDir("tomcat")); tomcat.setba
seDir(ba
seDir.getAbsolutePath()); Co
nnector co
nnector = new Co
nnector(this.protocol); tomcat.getService().addCo
nnector(connector); customizeCo
nnector(connector); tomcat.setCo
nnector(connector); tomcat.getHost().setAutoDeploy(false); co
nfigureEngine(tomcat.getEngine()); for (Co
nnector additio
nalConnector : this.additionalTomcatConnectors) { tomcat.getService().addCo
nnector(additionalConnector); } prepareCo
ntext(tomcat.getHost(), initializers); return getTomcatWebServer(tomcat); }protected TomcatWebServer getTomcatWebServer(Tomcat tomcat) { return new TomcatWebServer(tomcat, getPort() >= 0); }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): " + getPortsDes
cription(false)); synchro
nized (this.monitor) { try { addInstanceIdToEngineName(); Co
ntext co
ntext = findCo
ntext(); context.addLifecycleListener((event) -> { if (context.equals(event.getSource()) && Lifecycle.START_EVENT.equals(event.getType())) { // Remove service co
nnectors so that protocol binding doesn\\\'t // happen when the service is started. removeServiceCo
nnectors(); } }); // Start the server to trigger initialization listeners this.tomcat.start(); // We can re-throw failure exception directly in the main thread rethrowDeferredStartupExceptions(); try { ContextBindings.bindClassLoader(context, context.getNamingToken(), getClass().getClassLoader()); } catch (NamingException ex) { // Naming is not enabled. Co
ntinue } // Unlike Jetty, all Tomcat threads are daemon threads. We create a // blocking non-daemon to stop immediate shutdown startDaemo
nAwaitThread(); } catch (Exception ex) { throw new WebServerException("Unable to start embedded Tomcat", ex); } } }