spring boot启动加载tomcat原理深度剖析
1. 前言
????spring boot打包成fat jar的形式啟動時,這時tomcat作為內嵌容器,由spring boot帶動起來,并注冊servlet/filter等,這個過程是如何實現的呢?本文將從源碼級別帶你探索spring boot帶起tomcat的實現原理。
????以spring boot demo這個模塊為例,一步一步深入挖掘,著重看內嵌tomcat如何啟動,并講下外部tomcat啟動spring boot的原理。
2. 在bean definition加載完畢后,啟動并初始化tomcat
????一般情況下,我們是使用的是servlet,這時spring boot使用的是AnnotationConfigServletWebServerApplicationContext,繼承自ServletWebServerApplicationContext,這個父類,對AbstractApplicationContext的onRefresh方法進行了覆蓋,在這個階段加載了tomcat容器。
@Overrideprotected void onRefresh() {super.onRefresh();try {createWebServer();}catch (Throwable ex) {throw new ApplicationContextException("Unable to start web server", ex);}}????那么,選擇在這個擴展點創建的好處是什么呢?在onRefresh之前,已經使用BeanFactoryPostProcessor加載了所有的BeanDefinition,這個時候ApplicationContext可以getBean,獲取到ServletContext的初始化器,例如servlet/filter等spring bean初始化器,對tomcat進行配置。
????如下為創建tomcat的代碼,可以發現代碼有兩個分支,剛好分為內外tomcat兩種情況,內部tomcat的話,會進行創建并初始化;而外部tomcat僅僅會進行初始化,配置serlvet/filter等。
3. 外部tomcat加載SpringApplication
????以war包的形式打包時,這個時候需要單獨部署外部tomcat,由tomcat帶動spring boot容器。
????從代碼可以發現,外部tomcat的話,servletContext必然是賦值的,這里是在哪賦值呢?外部tomcat留了什么鉤子,可以讓spring來編程初始化servelt/filter呢?
????對于外部tomcat部署spring boot應用,我們會讓main類繼承SpringBootServletInitializer,這是一個WebApplicationInitializer,是spring對于servlet的擴展點。在tomcat啟動時,會調用其onStartup方法,創建SpringApplication,設置初始化器,最終會設置servletContext,完成整個SpringApplication的構建。
????那么SpringBootServletInitializer#onStartup這個方法,是在哪調用的呢?是SpringServletContainerInitializer,通過注釋可以看到,因為這個類上有@HandlesTypes注解,指定了類接口WebApplicationInitializer,servlet 3.0容器會自動掃描類路徑下的WebApplicationInitializer實現類,并把掃描到的實現類集合作為第一個參數傳遞給SpringServletContainerInitializer。
@HandlesTypes(WebApplicationInitializer.class) public class SpringServletContainerInitializer implements ServletContainerInitializer {/*** Delegate the {@code ServletContext} to any {@link WebApplicationInitializer}* implementations present on the application classpath.* <p>Because this class declares @{@code HandlesTypes(WebApplicationInitializer.class)},* Servlet 3.0+ containers will automatically scan the classpath for implementations* of Spring's {@code WebApplicationInitializer} interface and provide the set of all* such types to the {@code webAppInitializerClasses} parameter of this method.* <p>If no {@code WebApplicationInitializer} implementations are found on the classpath,* this method is effectively a no-op. An INFO-level log message will be issued notifying* the user that the {@code ServletContainerInitializer} has indeed been invoked but that* no {@code WebApplicationInitializer} implementations were found.* <p>Assuming that one or more {@code WebApplicationInitializer} types are detected,* they will be instantiated (and <em>sorted</em> if the @{@link* org.springframework.core.annotation.Order @Order} annotation is present or* the {@link org.springframework.core.Ordered Ordered} interface has been* implemented). Then the {@link WebApplicationInitializer#onStartup(ServletContext)}* method will be invoked on each instance, delegating the {@code ServletContext} such* that each instance may register and configure servlets such as Spring's* {@code DispatcherServlet}, listeners such as Spring's {@code ContextLoaderListener},* or any other Servlet API componentry such as filters.* @param webAppInitializerClasses all implementations of* {@link WebApplicationInitializer} found on the application classpath* @param servletContext the servlet context to be initialized* @see WebApplicationInitializer#onStartup(ServletContext)* @see AnnotationAwareOrderComparator*/@Overridepublic void onStartup(@Nullable Set<Class<?>> webAppInitializerClasses, ServletContext servletContext)throws ServletException {List<WebApplicationInitializer> initializers = Collections.emptyList();if (webAppInitializerClasses != null) {initializers = new ArrayList<>(webAppInitializerClasses.size());for (Class<?> waiClass : webAppInitializerClasses) {// Be defensive: Some servlet containers provide us with invalid classes,// no matter what @HandlesTypes says...if (!waiClass.isInterface() && !Modifier.isAbstract(waiClass.getModifiers()) &&WebApplicationInitializer.class.isAssignableFrom(waiClass)) {try {initializers.add((WebApplicationInitializer)ReflectionUtils.accessibleConstructor(waiClass).newInstance());}catch (Throwable ex) {throw new ServletException("Failed to instantiate WebApplicationInitializer class", ex);}}}}if (initializers.isEmpty()) {servletContext.log("No Spring WebApplicationInitializer types detected on classpath");return;}servletContext.log(initializers.size() + " Spring WebApplicationInitializers detected on classpath");AnnotationAwareOrderComparator.sort(initializers);for (WebApplicationInitializer initializer : initializers) {// servlet會找到所有的WebApplicationInitializer SPI,然后調用,其中就包括SpringBootServletInitializer的實現類initializer.onStartup(servletContext);}}}package javax.servlet;import java.util.Set;/*** ServletContainerInitializers (SCIs) are registered via an entry in the* file META-INF/services/javax.servlet.ServletContainerInitializer that must be* included in the JAR file that contains the SCI implementation.* <p>* SCI processing is performed regardless of the setting of metadata-complete.* SCI processing can be controlled per JAR file via fragment ordering. If* absolute ordering is defined, then only the JARs included in the ordering* will be processed for SCIs. To disable SCI processing completely, an empty* absolute ordering may be defined.* <p>* SCIs register an interest in annotations (class, method or field) and/or* types via the {@link javax.servlet.annotation.HandlesTypes} annotation which* is added to the class.** @since Servlet 3.0*/ public interface ServletContainerInitializer {/*** Receives notification during startup of a web application of the classes* within the web application that matched the criteria defined via the* {@link javax.servlet.annotation.HandlesTypes} annotation.** @param c The (possibly null) set of classes that met the specified* criteria* @param ctx The ServletContext of the web application in which the* classes were discovered** @throws ServletException If an error occurs*/void onStartup(Set<Class<?>> c, ServletContext ctx) throws ServletException; }????對應的java spi如下,在spring web中實現了servlet標準的擴展點ServletContainerInitializer,該擴展點從3.0開始,且是為了替換web.xml而生的。
????一張圖總結外部tomcat啟動時,加載SpringApplication的整個過程:
4. fat jar啟動內嵌tomcat
????如下,會從spring容器查找ServletWebServerFactory,然后調用其getWebServer方法,并把ServletContextInitializer初始化器傳遞進去。
//org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext#createWebServerprivate void createWebServer() {WebServer webServer = this.webServer;ServletContext servletContext = getServletContext();if (webServer == null && servletContext == null) {StartupStep createWebServer = this.getApplicationStartup().start("spring.boot.webserver.create");ServletWebServerFactory factory = getWebServerFactory();createWebServer.tag("factory", factory.getClass().toString());this.webServer = factory.getWebServer(getSelfInitializer());createWebServer.end();// (3)注冊Lifecycle,啟動后注冊到consul/nacos,以及優雅銷毀getBeanFactory().registerSingleton("webServerGracefulShutdown",new WebServerGracefulShutdownLifecycle(this.webServer));getBeanFactory().registerSingleton("webServerStartStop",new WebServerStartStopLifecycle(this, this.webServer));}else if (servletContext != null) {try {getSelfInitializer().onStartup(servletContext);}catch (ServletException ex) {throw new ApplicationContextException("Cannot initialize servlet context", ex);}}initPropertySources();}protected ServletWebServerFactory getWebServerFactory() {// Use bean names so that we don't consider the hierarchyString[] beanNames = getBeanFactory().getBeanNamesForType(ServletWebServerFactory.class);if (beanNames.length == 0) {throw new ApplicationContextException("Unable to start ServletWebServerApplicationContext due to missing "+ "ServletWebServerFactory bean.");}if (beanNames.length > 1) {throw new ApplicationContextException("Unable to start ServletWebServerApplicationContext due to multiple "+ "ServletWebServerFactory beans : " + StringUtils.arrayToCommaDelimitedString(beanNames));}return getBeanFactory().getBean(beanNames[0], ServletWebServerFactory.class);}????在ServletWebServerFactoryConfiguration這個配置類里,如果有tomcat這個jar,會自動注入tomcat factory,也就是TomcatServletWebServerFactory。ServletWebServerFactoryConfiguration類由ServletWebServerFactoryAutoConfiguration這個自動配置類導入。
@Configuration(proxyBeanMethods = false) class ServletWebServerFactoryConfiguration {@Configuration(proxyBeanMethods = false)@ConditionalOnClass({ Servlet.class, Tomcat.class, UpgradeProtocol.class })@ConditionalOnMissingBean(value = ServletWebServerFactory.class, search = SearchStrategy.CURRENT)static class EmbeddedTomcat {// 注冊tomcat ,可以自定義配置,這里會加載進來@BeanTomcatServletWebServerFactory tomcatServletWebServerFactory(ObjectProvider<TomcatConnectorCustomizer> connectorCustomizers,ObjectProvider<TomcatContextCustomizer> contextCustomizers,ObjectProvider<TomcatProtocolHandlerCustomizer<?>> protocolHandlerCustomizers) {TomcatServletWebServerFactory factory = new TomcatServletWebServerFactory();factory.getTomcatConnectorCustomizers().addAll(connectorCustomizers.orderedStream().collect(Collectors.toList()));factory.getTomcatContextCustomizers().addAll(contextCustomizers.orderedStream().collect(Collectors.toList()));factory.getTomcatProtocolHandlerCustomizers().addAll(protocolHandlerCustomizers.orderedStream().collect(Collectors.toList()));return factory;}}/*** Nested configuration if Jetty is being used.*/@Configuration(proxyBeanMethods = false)@ConditionalOnClass({ Servlet.class, Server.class, Loader.class, WebAppContext.class })@ConditionalOnMissingBean(value = ServletWebServerFactory.class, search = SearchStrategy.CURRENT)static class EmbeddedJetty {@BeanJettyServletWebServerFactory JettyServletWebServerFactory(ObjectProvider<JettyServerCustomizer> serverCustomizers) {JettyServletWebServerFactory factory = new JettyServletWebServerFactory();factory.getServerCustomizers().addAll(serverCustomizers.orderedStream().collect(Collectors.toList()));return factory;}}/*** Nested configuration if Undertow is being used.*/@Configuration(proxyBeanMethods = false)@ConditionalOnClass({ Servlet.class, Undertow.class, SslClientAuthMode.class })@ConditionalOnMissingBean(value = ServletWebServerFactory.class, search = SearchStrategy.CURRENT)static class EmbeddedUndertow {@BeanUndertowServletWebServerFactory undertowServletWebServerFactory(ObjectProvider<UndertowDeploymentInfoCustomizer> deploymentInfoCustomizers,ObjectProvider<UndertowBuilderCustomizer> builderCustomizers) {UndertowServletWebServerFactory factory = new UndertowServletWebServerFactory();factory.getDeploymentInfoCustomizers().addAll(deploymentInfoCustomizers.orderedStream().collect(Collectors.toList()));factory.getBuilderCustomizers().addAll(builderCustomizers.orderedStream().collect(Collectors.toList()));return factory;}@BeanUndertowServletWebServerFactoryCustomizer undertowServletWebServerFactoryCustomizer(ServerProperties serverProperties) {return new UndertowServletWebServerFactoryCustomizer(serverProperties);}}}@Configuration(proxyBeanMethods = false) @AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE) @ConditionalOnClass(ServletRequest.class) @ConditionalOnWebApplication(type = Type.SERVLET) @EnableConfigurationProperties(ServerProperties.class) @Import({ ServletWebServerFactoryAutoConfiguration.BeanPostProcessorsRegistrar.class,ServletWebServerFactoryConfiguration.EmbeddedTomcat.class,ServletWebServerFactoryConfiguration.EmbeddedJetty.class,ServletWebServerFactoryConfiguration.EmbeddedUndertow.class }) public class ServletWebServerFactoryAutoConfiguration {// 注冊bean,可以自定義容器設置,例如端口號@Beanpublic ServletWebServerFactoryCustomizer servletWebServerFactoryCustomizer(ServerProperties serverProperties,ObjectProvider<WebListenerRegistrar> webListenerRegistrars,ObjectProvider<CookieSameSiteSupplier> cookieSameSiteSuppliers) {return new ServletWebServerFactoryCustomizer(serverProperties,webListenerRegistrars.orderedStream().collect(Collectors.toList()),cookieSameSiteSuppliers.orderedStream().collect(Collectors.toList()));}@Bean@ConditionalOnClass(name = "org.apache.catalina.startup.Tomcat")public TomcatServletWebServerFactoryCustomizer tomcatServletWebServerFactoryCustomizer(ServerProperties serverProperties) {return new TomcatServletWebServerFactoryCustomizer(serverProperties);}@Configuration(proxyBeanMethods = false)@ConditionalOnProperty(value = "server.forward-headers-strategy", havingValue = "framework")@ConditionalOnMissingFilterBean(ForwardedHeaderFilter.class)static class ForwardedHeaderFilterConfiguration {@Bean@ConditionalOnClass(name = "org.apache.catalina.startup.Tomcat")@ConditionalOnMissingFilterBean(ForwardedHeaderFilter.class)ForwardedHeaderFilterCustomizer tomcatForwardedHeaderFilterCustomizer(ServerProperties serverProperties) {return (filter) -> filter.setRelativeRedirects(serverProperties.getTomcat().isUseRelativeRedirects());}@BeanFilterRegistrationBean<ForwardedHeaderFilter> forwardedHeaderFilter(ObjectProvider<ForwardedHeaderFilterCustomizer> customizerProvider) {ForwardedHeaderFilter filter = new ForwardedHeaderFilter();customizerProvider.ifAvailable((customizer) -> customizer.customize(filter));FilterRegistrationBean<ForwardedHeaderFilter> registration = new FilterRegistrationBean<>(filter);registration.setDispatcherTypes(DispatcherType.REQUEST, DispatcherType.ASYNC, DispatcherType.ERROR);registration.setOrder(Ordered.HIGHEST_PRECEDENCE);return registration;}}interface ForwardedHeaderFilterCustomizer {void customize(ForwardedHeaderFilter filter);}/*** Registers a {@link WebServerFactoryCustomizerBeanPostProcessor}. Registered via* {@link ImportBeanDefinitionRegistrar} for early registration.*/public static class BeanPostProcessorsRegistrar implements ImportBeanDefinitionRegistrar, BeanFactoryAware {private ConfigurableListableBeanFactory beanFactory;@Overridepublic void setBeanFactory(BeanFactory beanFactory) throws BeansException {if (beanFactory instanceof ConfigurableListableBeanFactory) {this.beanFactory = (ConfigurableListableBeanFactory) beanFactory;}}@Overridepublic void registerBeanDefinitions(AnnotationMetadata importingClassMetadata,BeanDefinitionRegistry registry) {if (this.beanFactory == null) {return;}// 注冊WebServerFactoryCustomizerBeanPostProcessor,對webServerFactory進行初始化registerSyntheticBeanIfMissing(registry, "webServerFactoryCustomizerBeanPostProcessor",WebServerFactoryCustomizerBeanPostProcessor.class,WebServerFactoryCustomizerBeanPostProcessor::new);registerSyntheticBeanIfMissing(registry, "errorPageRegistrarBeanPostProcessor",ErrorPageRegistrarBeanPostProcessor.class, ErrorPageRegistrarBeanPostProcessor::new);}private <T> void registerSyntheticBeanIfMissing(BeanDefinitionRegistry registry, String name,Class<T> beanClass, Supplier<T> instanceSupplier) {if (ObjectUtils.isEmpty(this.beanFactory.getBeanNamesForType(beanClass, true, false))) {RootBeanDefinition beanDefinition = new RootBeanDefinition(beanClass, instanceSupplier);beanDefinition.setSynthetic(true);registry.registerBeanDefinition(name, beanDefinition);}}}}4.1 初始化WebServerFactory,添加connector等初始化器
????在WebServerFactory構造時,借助bean后處理器WebServerFactoryCustomizerBeanPostProcessor,會利用WebServerFactoryCustomizer對應類型的bean對其進行初始化。內嵌tomcat時,可以通過application.yaml對tomcat容器的參數進行配置。外部tomcat時application.yaml關于tomcat的配置不生效
- TomcatWebSocketServletWebServerCustomizer,添加websocket ServerEndpoint相關處理器
- ServletWebServerFactoryCustomizer,主要是將yaml中配置的端口,設置到factory里。
- TomcatServletWebServerFactoryCustomizer,設置重定向相關。
- TomcatWebServerFactoryCustomizer,tomcat特定配置,核心配置,如線程池大小,訪問日志,連接大小,請求頭大小,錯誤路徑等。
4.2 創建tomcat
????主要是配置tomcat,類似server.xml,構建Connector,配置引擎。將4.1里設置到factory的初始化器,真正應用到tomcat配置上,例如最大線程數。
// org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory#getWebServer@Overridepublic WebServer getWebServer(ServletContextInitializer... initializers) {if (this.disableMBeanRegistry) {Registry.disableRegistry();}Tomcat tomcat = new Tomcat();File baseDir = (this.baseDirectory != null) ? this.baseDirectory : createTempDir("tomcat");tomcat.setBaseDir(baseDir.getAbsolutePath());for (LifecycleListener listener : this.serverLifecycleListeners) {tomcat.getServer().addLifecycleListener(listener);}Connector connector = new Connector(this.protocol);connector.setThrowOnFailure(true);tomcat.getService().addConnector(connector);customizeConnector(connector);tomcat.setConnector(connector);tomcat.getHost().setAutoDeploy(false);configureEngine(tomcat.getEngine());for (Connector additionalConnector : this.additionalTomcatConnectors) {tomcat.getService().addConnector(additionalConnector);}prepareContext(tomcat.getHost(), initializers);return getTomcatWebServer(tomcat);}// Needs to be protected so it can be used by subclassesprotected void customizeConnector(Connector connector) {int port = Math.max(getPort(), 0);// 設置端口到connectorconnector.setPort(port);if (StringUtils.hasText(getServerHeader())) {connector.setProperty("server", getServerHeader());}if (connector.getProtocolHandler() instanceof AbstractProtocol) {customizeProtocol((AbstractProtocol<?>) connector.getProtocolHandler());}invokeProtocolHandlerCustomizers(connector.getProtocolHandler());if (getUriEncoding() != null) {connector.setURIEncoding(getUriEncoding().name());}// Don't bind to the socket prematurely if ApplicationContext is slow to startconnector.setProperty("bindOnInit", "false");if (getHttp2() != null && getHttp2().isEnabled()) {connector.addUpgradeProtocol(new Http2Protocol());}if (getSsl() != null && getSsl().isEnabled()) {customizeSsl(connector);}TomcatConnectorCustomizer compression = new CompressionConnectorCustomizer(getCompression());compression.customize(connector);for (TomcatConnectorCustomizer customizer : this.tomcatConnectorCustomizers) {// 設置線程池,請求頭大小等customizer.customize(connector);}}protected void configureContext(Context context, ServletContextInitializer[] initializers) {// 添加初始化器TomcatStarter starter = new TomcatStarter(initializers);if (context instanceof TomcatEmbeddedContext) {TomcatEmbeddedContext embeddedContext = (TomcatEmbeddedContext) context;embeddedContext.setStarter(starter);embeddedContext.setFailCtxIfServletStartFails(true);}// TomcatStarter實現了ServletContainerInitializer,啟動后會觸發context.addServletContainerInitializer(starter, NO_CLASSES);for (LifecycleListener lifecycleListener : this.contextLifecycleListeners) {context.addLifecycleListener(lifecycleListener);}for (Valve valve : this.contextValves) {context.getPipeline().addValve(valve);}for (ErrorPage errorPage : getErrorPages()) {org.apache.tomcat.util.descriptor.web.ErrorPage tomcatErrorPage = new org.apache.tomcat.util.descriptor.web.ErrorPage();tomcatErrorPage.setLocation(errorPage.getPath());tomcatErrorPage.setErrorCode(errorPage.getStatusCode());tomcatErrorPage.setExceptionType(errorPage.getExceptionName());context.addErrorPage(tomcatErrorPage);}for (MimeMappings.Mapping mapping : getMimeMappings()) {context.addMimeMapping(mapping.getExtension(), mapping.getMimeType());}configureSession(context);configureCookieProcessor(context);new DisableReferenceClearingContextCustomizer().customize(context);for (String webListenerClassName : getWebListenerClassNames()) {context.addApplicationListener(webListenerClassName);}for (TomcatContextCustomizer customizer : this.tomcatContextCustomizers) {customizer.customize(context);}}/*** Factory method called to create the {@link TomcatWebServer}. Subclasses can* override this method to return a different {@link TomcatWebServer} or apply* additional processing to the Tomcat server.* @param tomcat the Tomcat server.* @return a new {@link TomcatWebServer} instance*/protected TomcatWebServer getTomcatWebServer(Tomcat tomcat) {return new TomcatWebServer(tomcat, getPort() >= 0, getShutdown());}4.3 ServletContextInitializer配置tomcat
????在TomcatWebServer的實例化過程的最后一步,會調用tomcat.start()方法,觸發initializer初始化servlet,內嵌tomcat由TomcatStarter觸發,因為TomcatStarter實現了ServletContainerInitializer,且也添加到了Tomcat上。外部tomcat時ApplicationContext#onRefresh直接調用這里,這里統一講解。
// TomcatWebServerpublic TomcatWebServer(Tomcat tomcat, boolean autoStart, Shutdown shutdown) {Assert.notNull(tomcat, "Tomcat Server must not be null");this.tomcat = tomcat;this.autoStart = autoStart;this.gracefulShutdown = (shutdown == Shutdown.GRACEFUL) ? new GracefulShutdown(tomcat) : null;initialize();}private void initialize() throws WebServerException {logger.info("Tomcat initialized with port(s): " + getPortsDescription(false));synchronized (this.monitor) {try {addInstanceIdToEngineName();Context context = findContext();context.addLifecycleListener((event) -> {if (context.equals(event.getSource()) && Lifecycle.START_EVENT.equals(event.getType())) {// Remove service connectors so that protocol binding doesn't// happen when the service is started.removeServiceConnectors();}});// Start the server to trigger initialization listenersthis.tomcat.start();// We can re-throw failure exception directly in the main threadrethrowDeferredStartupExceptions();try {ContextBindings.bindClassLoader(context, context.getNamingToken(), getClass().getClassLoader());}catch (NamingException ex) {// Naming is not enabled. Continue}// Unlike Jetty, all Tomcat threads are daemon threads. We create a// blocking non-daemon to stop immediate shutdownstartDaemonAwaitThread();}catch (Exception ex) {stopSilently();destroySilently();throw new WebServerException("Unable to start embedded Tomcat", ex);}}}????其中,有個initializer,在TomcatServletWebServerFactory創建tomcat server時傳入,是個lambda表達式適配的,也就是:
// ServletWebServerApplicationContextprivate org.springframework.boot.web.servlet.ServletContextInitializer getSelfInitializer() {return this::selfInitialize;}private void selfInitialize(ServletContext servletContext) throws ServletException {prepareWebApplicationContext(servletContext);// 設置servletContext的root app context屬性registerApplicationScope(servletContext);WebApplicationContextUtils.registerEnvironmentBeans(getBeanFactory(), servletContext);// 核心,從beanfactory,找到所有的ServletContextInitializer,并注冊到ServletContext中。for (ServletContextInitializer beans : getServletContextInitializerBeans()) {beans.onStartup(servletContext);}}/*** Returns {@link ServletContextInitializer}s that should be used with the embedded* web server. By default this method will first attempt to find* {@link ServletContextInitializer}, {@link Servlet}, {@link Filter} and certain* {@link EventListener} beans.* @return the servlet initializer beans*/protected Collection<ServletContextInitializer> getServletContextInitializerBeans() {return new ServletContextInitializerBeans(getBeanFactory());}????ServletContextInitializerBeans會加載ServletContextInitializer類型的bean。在spring boot中,實現了一個基類,也就是RegistrationBean,實現了ServletContextInitializer,底層抽象了配置一個對象到servletContext的過程,大部分servlet/filter都可以使用RegistrationBean相應子類實現注冊。
@SuppressWarnings("varargs")public ServletContextInitializerBeans(ListableBeanFactory beanFactory,Class<? extends ServletContextInitializer>... initializerTypes) {this.initializers = new LinkedMultiValueMap<>();this.initializerTypes = (initializerTypes.length != 0) ? Arrays.asList(initializerTypes): Collections.singletonList(ServletContextInitializer.class);// (1) 加載所有ServletContextInitializer類型的bean,并設置到initializers中addServletContextInitializerBeans(beanFactory);// (2) 添加適配類addAdaptableBeans(beanFactory);// 對initializers進行排序,外層會全部應用到initializer.onStartUp(serverltContext)List<ServletContextInitializer> sortedInitializers = this.initializers.values().stream().flatMap((value) -> value.stream().sorted(AnnotationAwareOrderComparator.INSTANCE)).collect(Collectors.toList());this.sortedList = Collections.unmodifiableList(sortedInitializers);logMappings(this.initializers);}????RegistrationBean繼承體系,onStartUp分為兩部,先添加到serveltContext,然后使用返回的registration對添加的對象做進一步配置,例如配置映射路徑
public abstract class RegistrationBean implements ServletContextInitializer, Ordered {private static final Log logger = LogFactory.getLog(RegistrationBean.class);private int order = Ordered.LOWEST_PRECEDENCE;private boolean enabled = true;@Overridepublic final void onStartup(ServletContext servletContext) throws ServletException {String description = getDescription();if (!isEnabled()) {logger.info(StringUtils.capitalize(description) + " was not registered (disabled)");return;}register(description, servletContext);}/*** Return a description of the registration. For example "Servlet resourceServlet"* @return a description of the registration*/protected abstract String getDescription();/*** Register this bean with the servlet context.* @param description a description of the item being registered* @param servletContext the servlet context*/protected abstract void register(String description, ServletContext servletContext);/*** Flag to indicate that the registration is enabled.* @param enabled the enabled to set*/public void setEnabled(boolean enabled) {this.enabled = enabled;}/*** Return if the registration is enabled.* @return if enabled (default {@code true})*/public boolean isEnabled() {return this.enabled;}/*** Set the order of the registration bean.* @param order the order*/public void setOrder(int order) {this.order = order;}/*** Get the order of the registration bean.* @return the order*/@Overridepublic int getOrder() {return this.order;}}public abstract class DynamicRegistrationBean<D extends Registration.Dynamic> extends RegistrationBean {private static final Log logger = LogFactory.getLog(RegistrationBean.class);private String name;private boolean asyncSupported = true;private Map<String, String> initParameters = new LinkedHashMap<>();/*** Set the name of this registration. If not specified the bean name will be used.* @param name the name of the registration*/public void setName(String name) {Assert.hasLength(name, "Name must not be empty");this.name = name;}/*** Sets if asynchronous operations are supported for this registration. If not* specified defaults to {@code true}.* @param asyncSupported if async is supported*/public void setAsyncSupported(boolean asyncSupported) {this.asyncSupported = asyncSupported;}/*** Returns if asynchronous operations are supported for this registration.* @return if async is supported*/public boolean isAsyncSupported() {return this.asyncSupported;}/*** Set init-parameters for this registration. Calling this method will replace any* existing init-parameters.* @param initParameters the init parameters* @see #getInitParameters* @see #addInitParameter*/public void setInitParameters(Map<String, String> initParameters) {Assert.notNull(initParameters, "InitParameters must not be null");this.initParameters = new LinkedHashMap<>(initParameters);}/*** Returns a mutable Map of the registration init-parameters.* @return the init parameters*/public Map<String, String> getInitParameters() {return this.initParameters;}/*** Add a single init-parameter, replacing any existing parameter with the same name.* @param name the init-parameter name* @param value the init-parameter value*/public void addInitParameter(String name, String value) {Assert.notNull(name, "Name must not be null");this.initParameters.put(name, value);}@Overrideprotected final void register(String description, ServletContext servletContext) {D registration = addRegistration(description, servletContext);if (registration == null) {logger.info(StringUtils.capitalize(description) + " was not registered (possibly already registered?)");return;}configure(registration);}protected abstract D addRegistration(String description, ServletContext servletContext);protected void configure(D registration) {// 添加到serveltContext后,可以使用返回的registration對添加的對象做進一步配置registration.setAsyncSupported(this.asyncSupported);if (!this.initParameters.isEmpty()) {registration.setInitParameters(this.initParameters);}}/*** Deduces the name for this registration. Will return user specified name or fallback* to convention based naming.* @param value the object used for convention based names* @return the deduced name*/protected final String getOrDeduceName(Object value) {return (this.name != null) ? this.name : Conventions.getVariableName(value);}}????按照序號(1),如果用戶沒有配置RegistrationBean的話,默認會添加三個bean:
4.3.1 添加默認的DispatcherServlet
????其中DispatcherServletAutoConfiguration在用戶未定義DispatcherSerlvet時自動注冊DispatcherServletRegistrationBean
@AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE) @Configuration(proxyBeanMethods = false) @ConditionalOnWebApplication(type = Type.SERVLET) @ConditionalOnClass(DispatcherServlet.class) @AutoConfigureAfter(ServletWebServerFactoryAutoConfiguration.class) public class DispatcherServletAutoConfiguration {/*** The bean name for a DispatcherServlet that will be mapped to the root URL "/".*/public static final String DEFAULT_DISPATCHER_SERVLET_BEAN_NAME = "dispatcherServlet";/*** The bean name for a ServletRegistrationBean for the DispatcherServlet "/".*/public static final String DEFAULT_DISPATCHER_SERVLET_REGISTRATION_BEAN_NAME = "dispatcherServletRegistration";@Configuration(proxyBeanMethods = false)@Conditional(DefaultDispatcherServletCondition.class)@ConditionalOnClass(ServletRegistration.class)@EnableConfigurationProperties(WebMvcProperties.class)protected static class DispatcherServletConfiguration {@Bean(name = DEFAULT_DISPATCHER_SERVLET_BEAN_NAME)public DispatcherServlet dispatcherServlet(WebMvcProperties webMvcProperties) {DispatcherServlet dispatcherServlet = new DispatcherServlet();dispatcherServlet.setDispatchOptionsRequest(webMvcProperties.isDispatchOptionsRequest());dispatcherServlet.setDispatchTraceRequest(webMvcProperties.isDispatchTraceRequest());dispatcherServlet.setThrowExceptionIfNoHandlerFound(webMvcProperties.isThrowExceptionIfNoHandlerFound());dispatcherServlet.setPublishEvents(webMvcProperties.isPublishRequestHandledEvents());dispatcherServlet.setEnableLoggingRequestDetails(webMvcProperties.isLogRequestDetails());return dispatcherServlet;}@Bean@ConditionalOnBean(MultipartResolver.class)@ConditionalOnMissingBean(name = DispatcherServlet.MULTIPART_RESOLVER_BEAN_NAME)public MultipartResolver multipartResolver(MultipartResolver resolver) {// Detect if the user has created a MultipartResolver but named it incorrectlyreturn resolver;}}@Configuration(proxyBeanMethods = false)@Conditional(DispatcherServletRegistrationCondition.class)@ConditionalOnClass(ServletRegistration.class)@EnableConfigurationProperties(WebMvcProperties.class)@Import(DispatcherServletConfiguration.class)protected static class DispatcherServletRegistrationConfiguration {@Bean(name = DEFAULT_DISPATCHER_SERVLET_REGISTRATION_BEAN_NAME)@ConditionalOnBean(value = DispatcherServlet.class, name = DEFAULT_DISPATCHER_SERVLET_BEAN_NAME)public DispatcherServletRegistrationBean dispatcherServletRegistration(DispatcherServlet dispatcherServlet,WebMvcProperties webMvcProperties, ObjectProvider<MultipartConfigElement> multipartConfig) {// 使用spring.mvc.servlet.path作為servlet映射路徑DispatcherServletRegistrationBean registration = new DispatcherServletRegistrationBean(dispatcherServlet,webMvcProperties.getServlet().getPath());registration.setName(DEFAULT_DISPATCHER_SERVLET_BEAN_NAME);registration.setLoadOnStartup(webMvcProperties.getServlet().getLoadOnStartup());multipartConfig.ifAvailable(registration::setMultipartConfig);return registration;}}@Order(Ordered.LOWEST_PRECEDENCE - 10)private static class DefaultDispatcherServletCondition extends SpringBootCondition {@Overridepublic ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) {ConditionMessage.Builder message = ConditionMessage.forCondition("Default DispatcherServlet");ConfigurableListableBeanFactory beanFactory = context.getBeanFactory();List<String> dispatchServletBeans = Arrays.asList(beanFactory.getBeanNamesForType(DispatcherServlet.class, false, false));if (dispatchServletBeans.contains(DEFAULT_DISPATCHER_SERVLET_BEAN_NAME)) {return ConditionOutcome.noMatch(message.found("dispatcher servlet bean").items(DEFAULT_DISPATCHER_SERVLET_BEAN_NAME));}if (beanFactory.containsBean(DEFAULT_DISPATCHER_SERVLET_BEAN_NAME)) {return ConditionOutcome.noMatch(message.found("non dispatcher servlet bean").items(DEFAULT_DISPATCHER_SERVLET_BEAN_NAME));}if (dispatchServletBeans.isEmpty()) {return ConditionOutcome.match(message.didNotFind("dispatcher servlet beans").atAll());}return ConditionOutcome.match(message.found("dispatcher servlet bean", "dispatcher servlet beans").items(Style.QUOTE, dispatchServletBeans).append("and none is named " + DEFAULT_DISPATCHER_SERVLET_BEAN_NAME));}}@Order(Ordered.LOWEST_PRECEDENCE - 10)private static class DispatcherServletRegistrationCondition extends SpringBootCondition {@Overridepublic ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) {ConfigurableListableBeanFactory beanFactory = context.getBeanFactory();ConditionOutcome outcome = checkDefaultDispatcherName(beanFactory);if (!outcome.isMatch()) {return outcome;}return checkServletRegistration(beanFactory);}private ConditionOutcome checkDefaultDispatcherName(ConfigurableListableBeanFactory beanFactory) {boolean containsDispatcherBean = beanFactory.containsBean(DEFAULT_DISPATCHER_SERVLET_BEAN_NAME);if (!containsDispatcherBean) {return ConditionOutcome.match();}List<String> servlets = Arrays.asList(beanFactory.getBeanNamesForType(DispatcherServlet.class, false, false));if (!servlets.contains(DEFAULT_DISPATCHER_SERVLET_BEAN_NAME)) {return ConditionOutcome.noMatch(startMessage().found("non dispatcher servlet").items(DEFAULT_DISPATCHER_SERVLET_BEAN_NAME));}return ConditionOutcome.match();}private ConditionOutcome checkServletRegistration(ConfigurableListableBeanFactory beanFactory) {ConditionMessage.Builder message = startMessage();List<String> registrations = Arrays.asList(beanFactory.getBeanNamesForType(ServletRegistrationBean.class, false, false));boolean containsDispatcherRegistrationBean = beanFactory.containsBean(DEFAULT_DISPATCHER_SERVLET_REGISTRATION_BEAN_NAME);if (registrations.isEmpty()) {if (containsDispatcherRegistrationBean) {return ConditionOutcome.noMatch(message.found("non servlet registration bean").items(DEFAULT_DISPATCHER_SERVLET_REGISTRATION_BEAN_NAME));}return ConditionOutcome.match(message.didNotFind("servlet registration bean").atAll());}if (registrations.contains(DEFAULT_DISPATCHER_SERVLET_REGISTRATION_BEAN_NAME)) {return ConditionOutcome.noMatch(message.found("servlet registration bean").items(DEFAULT_DISPATCHER_SERVLET_REGISTRATION_BEAN_NAME));}if (containsDispatcherRegistrationBean) {return ConditionOutcome.noMatch(message.found("non servlet registration bean").items(DEFAULT_DISPATCHER_SERVLET_REGISTRATION_BEAN_NAME));}return ConditionOutcome.match(message.found("servlet registration beans").items(Style.QUOTE, registrations).append("and none is named " + DEFAULT_DISPATCHER_SERVLET_REGISTRATION_BEAN_NAME));}private ConditionMessage.Builder startMessage() {return ConditionMessage.forCondition("DispatcherServlet Registration");}}}????spring-boot-actuator-autoconfigure包里的WebMvcMetricsAutoConfiguration引進WebMvcMetricsFilter registration
@Configuration(proxyBeanMethods = false) @AutoConfigureAfter({ MetricsAutoConfiguration.class, CompositeMeterRegistryAutoConfiguration.class,SimpleMetricsExportAutoConfiguration.class }) @ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET) @ConditionalOnClass(DispatcherServlet.class) @ConditionalOnBean(MeterRegistry.class) @EnableConfigurationProperties(MetricsProperties.class) public class WebMvcMetricsAutoConfiguration {private final MetricsProperties properties;public WebMvcMetricsAutoConfiguration(MetricsProperties properties) {this.properties = properties;}@Bean@ConditionalOnMissingBean(WebMvcTagsProvider.class)public DefaultWebMvcTagsProvider webMvcTagsProvider(ObjectProvider<WebMvcTagsContributor> contributors) {return new DefaultWebMvcTagsProvider(this.properties.getWeb().getServer().getRequest().isIgnoreTrailingSlash(),contributors.orderedStream().collect(Collectors.toList()));}@Beanpublic FilterRegistrationBean<WebMvcMetricsFilter> webMvcMetricsFilter(MeterRegistry registry,WebMvcTagsProvider tagsProvider) {ServerRequest request = this.properties.getWeb().getServer().getRequest();WebMvcMetricsFilter filter = new WebMvcMetricsFilter(registry, tagsProvider, request.getMetricName(),request.getAutotime());FilterRegistrationBean<WebMvcMetricsFilter> registration = new FilterRegistrationBean<>(filter);registration.setOrder(Ordered.HIGHEST_PRECEDENCE + 1);registration.setDispatcherTypes(DispatcherType.REQUEST, DispatcherType.ASYNC);return registration;}4.3.2 添加actuator endpoint servlet
????ServletEndpointRegistrar是actuator的servelt注冊器,其不走上面RegistrationBean,而是直接繼承了ServletContextInitializer。默認每個endpoint會單獨注冊成一個servlet。ServletEndpointRegistrar實際由ServletEndpointManagementContextConfiguration引進注冊成bean,涉及到endpoint的實現原理,另外講解。
// ServletEndpointRegistrarprivate void register(ServletContext servletContext, ExposableServletEndpoint endpoint) {String name = endpoint.getEndpointId().toLowerCaseString() + "-actuator-endpoint";String path = this.basePath + "/" + endpoint.getRootPath();String urlMapping = path.endsWith("/") ? path + "*" : path + "/*";EndpointServlet endpointServlet = endpoint.getEndpointServlet();Dynamic registration = servletContext.addServlet(name, endpointServlet.getServlet());registration.addMapping(urlMapping);registration.setInitParameters(endpointServlet.getInitParameters());registration.setLoadOnStartup(endpointServlet.getLoadOnStartup());logger.info("Registered '" + path + "' to " + name);}4.3.3 適配servlet/filter/listener類型的bean為RegistrationBean,并添加到servletContext
????在上面第(2)步中,還會添加servlet/filter類型的bean,包裝為RegistrationBean。
//org.springframework.boot.web.servlet.ServletContextInitializerBeans#addAdaptableBeansprotected void addAdaptableBeans(ListableBeanFactory beanFactory) {// multiconfig,上傳附件,MultipartConfigElement multipartConfig = getMultipartConfig(beanFactory);// 這里會在beanFactory里找Servlet的bean,排除已經被使用的DispatcherServlet,也就是source,包裝為Registration,并帶上multipartConfig配置addAsRegistrationBean(beanFactory, Servlet.class, new ServletRegistrationBeanAdapter(multipartConfig));// 將所有Filter類型的bean適配成FilterRegistrationBeanaddAsRegistrationBean(beanFactory, Filter.class, new FilterRegistrationBeanAdapter());// 將所有支持的listener適配成beanfor (Class<?> listenerType : ServletListenerRegistrationBean.getSupportedTypes()) {addAsRegistrationBean(beanFactory, EventListener.class, (Class<EventListener>) listenerType,new ServletListenerRegistrationBeanAdapter());}}????其中附件配置時默認自動配置,
public class MultipartAutoConfiguration {private final MultipartProperties multipartProperties;public MultipartAutoConfiguration(MultipartProperties multipartProperties) {this.multipartProperties = multipartProperties;}@Bean@ConditionalOnMissingBean({ MultipartConfigElement.class, CommonsMultipartResolver.class })public MultipartConfigElement multipartConfigElement() {return this.multipartProperties.createMultipartConfig();}????filter有三個,主要是字符編碼過濾器OrderedCharacterEncodingFilter,由HttpEncodingAutoConfiguration注入。RequestContextFilter主要是暴露ServletRequestAttributes到線程變量,也就是httpServletRequest和httpServletResponse,由WebMvcAutoConfiguration注入。
????將下面默認有7個 listener bean適配成ServletListenerRegistrationBean,默認沒有。
4.3.4 注冊到servletContext
????對于DispatcherServlet,DispatcherServletRegistrationBean會將其urlmapping/loadStartUp順序/multipartConfig配置到servletContext上去。
5. spring容器啟動后,注冊服務實例到consul
????在上面序號(3)中,創建嵌入tomcat成功(注意是內嵌tomcat),會手動注冊兩個bean,兩個bean均實現了SmartLifecycle接口,該接口屬于spring實現的生命周期接口,當前spring容器單例加載完成后和關閉前,會分別觸發對應的start和stop方法。如果有多個SmartLifecycle接口,按照phase從小到大調用start方法,按照phase從大到調用stop方法。注意不同版本的spring boot實現不同,但是整體是在spring容器單例加載完成后和關閉前觸發調用。
????WebServerStartStopLifecycle在spring單例刷新完畢后,會發送ServletWebServerInitializedEvent事件,spring cloud利用這個事件,實現了注冊當前服務實例到注冊中心的功能。具體可以看spring-cloud-common的AbstractAutoServiceRegistration。具體可見spring cloud demo,里面的consumer模塊。
????serviceId為spring.application.name,端口為tomcat端口。如果有management端口,一般也會進行注冊。
6. spring容器銷毀,停止tomcat和解除服務注冊
????在spring容器停止后,也就是收到信號,觸發shutdownhook,調用close時,按照不同spring boot版本,有兩種關閉順序,高版本spring boot:
- 先調用WebServerGracefulShutdownLifecycle(order大)優雅關閉,再調用WebServerStartStopLifecycle,停止tomcat。
- 之后才銷毀單例disposable bean。AbstractAutoServiceRegistration在銷毀時,會調用stop方法,解除注冊。
????低版本spring boot:
- 銷毀單例disposable bean。AbstractAutoServiceRegistration在銷毀時,會調用stop方法,解除注冊。
- 也就是所有單例都銷毀后,在AbstractApplicationContext#onClose進行,停止tomcat
????個人認為解除注冊放到第一步,在收到onClosedEvent時進行合理些,然后銷毀tomcat,最后再銷毀單例。
7. 內外tomcat與spring boot整體交互
????一張圖總結:
總結
以上是生活随笔為你收集整理的spring boot启动加载tomcat原理深度剖析的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: c++ 17介绍
- 下一篇: [hackinglab][CTF][上传