spring boot 加載web容器tomcat流程源碼分析
我本地的springboot版本是2.5.1,後面的分析都是基於這個版本
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.5.1</version> <relativePath/> <!-- lookup parent from repository --> </parent>
我們通過在pom文件中引入
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency>
來引入web容器,默認的web容器時tomcat。
本文章主要描述spring boot加載web容器 tomcat的部分,為瞭避免文章知識點過於分散,其他相關的如bean的加載,tomcat內部流程等不做深入討論。
1、在springboot web工程中,全局上下文是AnnotationConfigServletWebApplicationContext
下面的部分,我們具體來看下
首先,我們的入口代碼一般都是這樣寫的
public static void main(String[] args) { SpringApplication.run(BootargsApplication.class,args); }
跳轉到run方法裡面,依次會調用下面兩個方法
public static ConfigurableApplicationContext run(Class<?> primarySource, String... args) { return run(new Class<?>[] { primarySource }, args); }
public static ConfigurableApplicationContext run(Class<?>[] primarySources, String[] args) { return new SpringApplication(primarySources).run(args); }
首先會創建SpringApplication實例對象,跳轉到SpringApplication的構造方法去看看,依次會調用如下方法
public SpringApplication(Class<?>... primarySources) { this(null, primarySources); }
@SuppressWarnings({ "unchecked", "rawtypes" }) public SpringApplication(ResourceLoader resourceLoader, Class<?>... primarySources) { ...... //本次不相關的代碼全部省略掉,隻保留相關代碼 //這裡的 this.webApplicationType=WebApplicationType.SERVLET, 我們來分析下這個代碼的具體的執行賦值 this.webApplicationType = WebApplicationType.deduceFromClasspath(); ...... }
繼續跳轉到WebApplicationType.deduceFromClasspath()去看看
//這個方法主要是在當前類路徑下查找指定的class類是否存在,返回對飲枚舉類型 static WebApplicationType deduceFromClasspath() { // WEBMVC_INDICATOR_CLASS = "org.springframework.web.servlet.DispatcherServlet"; //我們通過pom文件引入spring-boot-starter-web,會簡介引入spring-webmvc,上面這個類就在這個webmvc中,所以不會進入這個if分支 if (ClassUtils.isPresent(WEBFLUX_INDICATOR_CLASS, null) && !ClassUtils.isPresent(WEBMVC_INDICATOR_CLASS, null) && !ClassUtils.isPresent(JERSEY_INDICATOR_CLASS, null)) { return WebApplicationType.REACTIVE; } //SERVLET_INDICATOR_CLASSES = { "javax.servlet.Servlet", "org.springframework.web.context.ConfigurableWebApplicationContext" } //javax.servlet.Servlet這個類存在於tomcat-embed-core中 //org.springframework.web.context.ConfigurableWebApplicationContext這個類存在於spring-web中 //這兩個jar都是由spring-boot-starter-web間接引入的,所以也不會走這個分支 for (String className : SERVLET_INDICATOR_CLASSES) { if (!ClassUtils.isPresent(className, null)) { return WebApplicationType.NONE; } } //所以會從這裡返回 return WebApplicationType.SERVLET; }
下面看下jar包的引入
回到new SpringApplication(primarySources).run(args)的調用來看run方法的代碼
public ConfigurableApplicationContext run(String... args) { ....... try { ...... //我們來看這個context的創建,context=new AnnotationConfigServletWebServerApplicationContext()下面來具體看這塊的執行 context = createApplicationContext(); ...... //後續幾個部分會來說明這個方法 refreshContext(context); ...... } catch (Throwable ex) { ...... } try { ....... } catch (Throwable ex) { ....... } return context; }
createApplicationContext()依次會調用如下方法
protected ConfigurableApplicationContext createApplicationContext() { //這裡的this.webApplicationType就是上面的WebApplicationType.SERVLET return this.applicationContextFactory.create(this.webApplicationType); }
//最終會調用到這個lambda表達式,入參就是上面的WebApplicationType.SERVLET ApplicationContextFactory DEFAULT = (webApplicationType) -> { try { switch (webApplicationType) { case SERVLET: //會從這裡返回 return new AnnotationConfigServletWebServerApplicationContext(); case REACTIVE: return new AnnotationConfigReactiveWebServerApplicationContext(); default: return new AnnotationConfigApplicationContext(); } } catch (Exception ex) { throw new IllegalStateException("Unable create a default ApplicationContext instance, " + "you may need a custom ApplicationContextFactory", ex); } };
到這裡,我們的上下文context就已經創建出來瞭,這塊代碼也比較簡單。就不多說什麼瞭
2、查找ServletWebServerFactory
再次回到new SpringApplication(primarySources).run(args)的調用來看run方法的代碼
public ConfigurableApplicationContext run(String... args) { ....... try { ...... //上面已經對context做過瞭講解,context=new AnnotationConfigServletWebServerApplicationContext() context = createApplicationContext(); ...... //下面來看這個方法 refreshContext(context); ...... } catch (Throwable ex) { ...... } try { ....... } catch (Throwable ex) { ....... } return context; }
點到refreshContext(context)
private void refreshContext(ConfigurableApplicationContext context) { if (this.registerShutdownHook) { shutdownHook.registerApplicationContext(context); } refresh(context); }
繼續點到refresh(context)
protected void refresh(ConfigurableApplicationContext applicationContext) { //這裡的applicationContext就是AnnotationConfigServletWebServerApplicationContext的對象,由於這個類沒有refresh方法,會跳轉到它的父類ServletWebServerApplicationContext的方法中去,我們繼續點進去 applicationContext.refresh(); }
點到ServletWebServerApplicationContext的refresh方法
public final void refresh() throws BeansException, IllegalStateException { try { //繼續跳轉到父類AbstractApplicationContext方法 super.refresh(); } catch (RuntimeException ex) { WebServer webServer = this.webServer; if (webServer != null) { webServer.stop(); } throw ex; } }
打開AbstractApplicationContext的refresh方法
//springboot 大部分的初始化工作是在這裡完成的,不過這不是我們本地的重點,不相關的我們統統略過 public void refresh() throws BeansException, IllegalStateException { synchronized (this.startupShutdownMonitor) { ...... try { ...... //繼續點到這個方法,這裡又會跳轉到ServletWebServerApplicationContext這個類的方法 onRefresh(); ..... } catch (BeansException ex) { ..... } finally { ..... } } }
打開ServletWebServerApplicationContext的onRefresh方法
protected void onRefresh() { super.onRefresh(); try { //這裡就是我們本次的重點,會在這裡創建具體的web容器,我們點進去看看,還是ServletWebServerApplicationContext這個類的方法 createWebServer(); } catch (Throwable ex) { throw new ApplicationContextException("Unable to start web server", ex); } }
打開ServletWebServerApplicationContext的createWebServer方法
private void createWebServer() { WebServer webServer = this.webServer; ServletContext servletContext = getServletContext(); //第一次進來webServer servletContext都是null,會進到if分支裡面 if (webServer == null && servletContext == null) { //這裡隻是做個標記,不用關註,跳過 StartupStep createWebServer = this.getApplicationStartup().start("spring.boot.webserver.create"); //這裡就會來查找ServletWebServerFactory,也就是web容器的工廠,具體看下getWebServerFactory()方法,還是ServletWebServerApplicationContext這個類的方法 ServletWebServerFactory factory = getWebServerFactory(); createWebServer.tag("factory", factory.getClass().toString()); this.webServer = factory.getWebServer(getSelfInitializer()); createWebServer.end(); 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(); }
打開ServletWebServerApplicationContext的getWebServerFactory方法
protected ServletWebServerFactory getWebServerFactory() { // Use bean names so that we don't consider the hierarchy //從beanFactory中查找ServletWebServerFactory類型的bean的定義,返回對應bean的名字 String[] 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)); } //這裡會從beanFactory中返回bean的名字為beanNames[0],類型為ServletWebServerFactory.class的bean對象,如果當前bean還未創建,則此時就會創建bean對象並返回 return getBeanFactory().getBean(beanNames[0], ServletWebServerFactory.class); }
從上面的代碼並看不出來實際的ServletWebServerFactory對象具體是什麼?下面帶著大傢一起簡單過下這部分的加載,這裡具體就是springboot 加載bean的流程瞭,這部分的邏輯比較多,本次就不具體展開。關於springboot 加載bean的流程計劃後續專門再寫一篇。
springboot在啟動過程中會在當前類路徑下META-INF/spring.factories這個文件中,key=org.springframework.boot.autoconfigure.EnableAutoConfiguration的屬性的作為bean的定義進行加載,在這過程中還會使用key=org.springframework.boot.autoconfigure.AutoConfigurationImportFilterfilter的屬性作為過濾,配合META-INF/spring-autoconfigure-metadata.properties對這些類做一個過濾,剔除掉不符合的類(後續還會根據類上的註解判斷是否要繼續剔除)。
當前這些主要在spring-boot-autoconfigure-2.5.1.jar這個文件中
下面截取上面說的兩部分,可以看到這裡的過濾器就3個,具體不展開討論瞭,自動導入的類就是下面的再加過濾去掉的
# Auto Configuration Import Filters org.springframework.boot.autoconfigure.AutoConfigurationImportFilter=\ org.springframework.boot.autoconfigure.condition.OnBeanCondition,\ org.springframework.boot.autoconfigure.condition.OnClassCondition,\ org.springframework.boot.autoconfigure.condition.OnWebApplicationCondition # Auto Configure org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ ...... #下面這個會在創建servelt中使用,下部分我們再關註它 org.springframework.boot.autoconfigure.web.servlet.DispatcherServletAutoConfiguration,\ #下面這個就是我們需要用到的 org.springframework.boot.autoconfigure.web.servlet.ServletWebServerFactoryAutoConfiguration,\ ...... org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration,\ ......
我們看下上面的org.springframework.boot.autoconfigure.web.servlet.ServletWebServerFactoryAutoConfiguration這個類,這個類在web 場景下,不會被剔除。會被加載。我們看看這個類,我們隻看頭部就可以瞭
這裡我們看到類上有Import註解,會繼續導入這幾個類,
ServletWebServerFactoryConfiguration.EmbeddedTomcat.class, ServletWebServerFactoryConfiguration.EmbeddedJetty.class, ServletWebServerFactoryConfiguration.EmbeddedUndertow.class
這三個都是本次相關的,它們都是ServletWebServerFactoryConfiguration的內部類,我們進去看看,類的結構都是一樣的,我們就看下ServletWebServerFactoryConfiguration.EmbeddedTomcat類吧
可以看到EmbeddedTomcat上面有ConditionalOnClass,ConditionalOnMissingBean這兩個註解,
簡單說下,ConditionalOnClass是表示當前類路徑下存在對應類是加載
ConditionalOnMissingBean是表示當前beanFactory中沒有對應類型bean定義的話加載
多個條件都是and的關系,有一個條件不成立,就不會去進行後續處理。
在這裡EmbeddedTomcat類這兩個條件是成立的,這時就會繼續遍歷當前類的所有方法,找到@Bean註解的方法,加載到beanFactory中去
而EmbeddedJetty,EmbeddedUndertow兩個類條件是不成立的,就不會進行後續執行,剔除掉瞭
這裡就會把EmbeddedTomcat.tomcatServletWebServerFactory這個方法進行加載,返回值是TomcatServletWebServerFactory類型,我們看下TomcatServletWebServerFactory類的繼承圖,可以看到它正好是繼承瞭ServletWebServerFactory接口。
再次打開ServletWebServerApplicationContext的getWebServerFactory方法
protected ServletWebServerFactory getWebServerFactory() { ....... //所以這裡的邏輯實際上會執行ServletWebServerFactoryConfiguration.EmbeddedTomcat類的tomcatServletWebServerFactory方法,返回TomcatServletWebServerFactory對象,相關的屬性註入等等這裡就不講述瞭 return getBeanFactory().getBean(beanNames[0], ServletWebServerFactory.class); }
到這裡,整個ServletWebServerFactory的查找就完成瞭
3、創建DispatcherServletRegistrationBean,DispatcherServlet
再看看上面的META-INF/spring.factories文件
# Auto Configuration Import Filters org.springframework.boot.autoconfigure.AutoConfigurationImportFilter=\ org.springframework.boot.autoconfigure.condition.OnBeanCondition,\ org.springframework.boot.autoconfigure.condition.OnClassCondition,\ org.springframework.boot.autoconfigure.condition.OnWebApplicationCondition # Auto Configure org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ ...... #現在我們重點來看這個類 org.springframework.boot.autoconfigure.web.servlet.DispatcherServletAutoConfiguration,\ org.springframework.boot.autoconfigure.web.servlet.ServletWebServerFactoryAutoConfiguration,\ ...... org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration,\ ......
我們打開org.springframework.boot.autoconfigure.web.servlet.DispatcherServletAutoConfiguration這個類看看
@AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE) @Configuration(proxyBeanMethods = false) //我們當前隻關註這ConditionalOnWebApplication、ConditionalOnClass註解 //ConditionalOnWebApplication是根據type來判斷指定類是否存在 //當前的type是 Type.SERVLET,是來查找org.springframework.web.context.support.GenericWebApplicationContext類是否存在,這個類存在於spring-web中,所以這個條件是true @ConditionalOnWebApplication(type = Type.SERVLET) //這個註解上面說過瞭 ,就是查找指定的類是否存在,這個是查找DispatcherServlet.class是否存在,這裡也會返回true @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) //這裡還是個條件,通過實現Condition接口,通過matches方法來判斷 //DefaultDispatcherServletCondition這個類就在當前這個文件裡,matches判斷的結果也是true @Conditional(DefaultDispatcherServletCondition.class) //ServletRegistration.class這個類存在於tomcat-embed-core裡面,這個結果也是true @ConditionalOnClass(ServletRegistration.class) //上面兩個條件成立,就會執行後續的操作,去遍歷內部類和方法 @EnableConfigurationProperties(WebMvcProperties.class) protected static class DispatcherServletConfiguration { //beanFactory會創建這個DispatcherServletbean的定義,bean的名字就是dispatcherServlet @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 incorrectly return resolver; } } @Configuration(proxyBeanMethods = false) //和上面的一樣,不說瞭 @Conditional(DispatcherServletRegistrationCondition.class) //和上面的一樣,不說瞭 @ConditionalOnClass(ServletRegistration.class) @EnableConfigurationProperties(WebMvcProperties.class) //這裡會要在查找DispatcherServletConfiguration.class,並執行加載bean定義的流程,這就是上面的類瞭 @Import(DispatcherServletConfiguration.class) protected static class DispatcherServletRegistrationConfiguration { @Bean(name = DEFAULT_DISPATCHER_SERVLET_REGISTRATION_BEAN_NAME) //ConditionalOnBean查找是否存在指定bean的定義,這個方法要註入參數,需要這個類,當前這裡就是上面的dispatcherServlet方法定義的,這裡也是存在的 @ConditionalOnBean(value = DispatcherServlet.class, name = DEFAULT_DISPATCHER_SERVLET_BEAN_NAME) //DispatcherServlet dispatcherServlet這個就是dispatcherServlet這個方法定義的bean,在創建DispatcherServletRegistrationBean這個bean的時候,就會去查找dispatcherServlet是否存在,如果不存在,先創建dispatcherServlet這個bean,再創建DispatcherServletRegistrationBean public DispatcherServletRegistrationBean dispatcherServletRegistration(DispatcherServlet dispatcherServlet, WebMvcProperties webMvcProperties, ObjectProvider<MultipartConfigElement> multipartConfig) { 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; } } ...... }
上面就是創建DispatcherServlet,DispatcherServletRegistrationBean的過程瞭
4、創建tomcat,加載Servlet.class,filter.class,監聽器
再次回到ServletWebServerApplicationContext的createWebServer方法
private void createWebServer() { WebServer webServer = this.webServer; ServletContext servletContext = getServletContext(); if (webServer == null && servletContext == null) { StartupStep createWebServer = this.getApplicationStartup().start("spring.boot.webserver.create"); //上面我們已經看到瞭這裡,factory是TomcatServletWebServerFactory類的一個實例對象 ServletWebServerFactory factory = getWebServerFactory(); //這裡還是做個標記,不用關註 createWebServer.tag("factory", factory.getClass().toString()); //這裡就是具體創建tomcat瞭,這裡的入參getSelfInitializer()是個lambda表達式,這個後續很重要 this.webServer = factory.getWebServer(getSelfInitializer()); createWebServer.end(); 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(); }
private org.springframework.boot.web.servlet.ServletContextInitializer getSelfInitializer() { return this::selfInitialize; } //是創建webServer的參數 private void selfInitialize(ServletContext servletContext) throws ServletException { prepareWebApplicationContext(servletContext); registerApplicationScope(servletContext); WebApplicationContextUtils.registerEnvironmentBeans(getBeanFactory(), servletContext); for (ServletContextInitializer beans : getServletContextInitializerBeans()) { beans.onStartup(servletContext); } }
factory.getWebServer(getSelfInitializer())會調用到TomcatServletWebServerFactory的getWebServer的方法
public WebServer getWebServer(ServletContextInitializer... initializers) { ....... //上面的入參會在這裡傳下去 prepareContext(tomcat.getHost(), initializers); return getTomcatWebServer(tomcat); }
點進prepareContext(tomcat.getHost(), initializers)去看看
protected void prepareContext(Host host, ServletContextInitializer[] initializers) { ...... ServletContextInitializer[] initializersToUse = mergeInitializers(initializers); host.addChild(context); //繼續傳下去 configureContext(context, initializersToUse); postProcessContext(context); }
再點到configureContext(context, initializersToUse)這個調用去看看
protected void configureContext(Context context, ServletContextInitializer[] initializers) { //會傳遞給TomcatStarter,作為構造參數,下面我們去這裡看看 TomcatStarter starter = new TomcatStarter(initializers); ...... }
下面我們去看看TomcatStarter這個類是怎麼使用這個initializers這個構造參數的。
這個類不長 class TomcatStarter implements ServletContainerInitializer { ...... TomcatStarter(ServletContextInitializer[] initializers) { //入參會作為它的成員屬性 this.initializers = initializers; } @Override public void onStartup(Set<Class<?>> classes, ServletContext servletContext) throws ServletException { try { for (ServletContextInitializer initializer : this.initializers) { //會在這裡調用onStartup方法,這裡的入參就是ApplicationContextFacade的對象,裡面包裝瞭ApplicationContext,裡面再包裝瞭TomcatEmbeddedContext,這要就和tomcat聯系起來瞭,下面的截圖就是servletContext的對象結構 initializer.onStartup(servletContext); } } catch (Exception ex) { ...... }
上面的initializer.onStartup(servletContext)會調用到ServletWebServerApplicationContext的selfInitialize方法
private void selfInitialize(ServletContext servletContext) throws ServletException { //這裡是將ApplicationContextFacade設置到當前的servletContext上 prepareWebApplicationContext(servletContext); //這裡是在beanFactory中註冊application的scope registerApplicationScope(servletContext); //這裡還是註冊上下文相關的bean WebApplicationContextUtils.registerEnvironmentBeans(getBeanFactory(), servletContext); //我們重點來看這裡getServletContextInitializerBeans()是定義個一個ServletContextInitializerBeans對象,我們點進去看看 for (ServletContextInitializer beans : getServletContextInitializerBeans()) { beans.onStartup(servletContext); } }
protected Collection<ServletContextInitializer> getServletContextInitializerBeans() { //這裡的getBeanFactory()就是全局的beanFactory return new ServletContextInitializerBeans(getBeanFactory()); }
public ServletContextInitializerBeans(ListableBeanFactory beanFactory, Class<? extends ServletContextInitializer>... initializerTypes) { this.initializers = new LinkedMultiValueMap<>(); //由於我們沒有傳initializerTypes這個參數,所以this.initializerTypes裡面就隻有ServletContextInitializer.class這個類 this.initializerTypes = (initializerTypes.length != 0) ? Arrays.asList(initializerTypes) : Collections.singletonList(ServletContextInitializer.class); //這裡主要是從beanFactory中查找this.initializerTypes類型,我們進去看看,就是下面這個方法瞭 addServletContextInitializerBeans(beanFactory); addAdaptableBeans(beanFactory); 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); } private void addServletContextInitializerBeans(ListableBeanFactory beanFactory) { for (Class<? extends ServletContextInitializer> initializerType : this.initializerTypes) { //默認情況下這裡找到就隻有上面第3部分的DispatcherServletRegistrationBean對應的bean for (Entry<String, ? extends ServletContextInitializer> initializerBean : getOrderedBeansOfType(beanFactory, initializerType)) { //這裡的key是bean的名字,value就是bean對象,在進去看看,就是下面這個方法 addServletContextInitializerBean(initializerBean.getKey(), initializerBean.getValue(), beanFactory); } } } private void addServletContextInitializerBean(String beanName, ServletContextInitializer initializer, ListableBeanFactory beanFactory) { //會走到這個分支 if (initializer instanceof ServletRegistrationBean) { //這裡返回的servlet也還是第3部分DispatcherServlet對應的bean Servlet source = ((ServletRegistrationBean<?>) initializer).getServlet(); //再點進去 addServletContextInitializerBean(Servlet.class, beanName, initializer, beanFactory, source); } else if (initializer instanceof FilterRegistrationBean) { Filter source = ((FilterRegistrationBean<?>) initializer).getFilter(); addServletContextInitializerBean(Filter.class, beanName, initializer, beanFactory, source); } else if (initializer instanceof DelegatingFilterProxyRegistrationBean) { String source = ((DelegatingFilterProxyRegistrationBean) initializer).getTargetBeanName(); addServletContextInitializerBean(Filter.class, beanName, initializer, beanFactory, source); } else if (initializer instanceof ServletListenerRegistrationBean) { EventListener source = ((ServletListenerRegistrationBean<?>) initializer).getListener(); addServletContextInitializerBean(EventListener.class, beanName, initializer, beanFactory, source); } else { addServletContextInitializerBean(ServletContextInitializer.class, beanName, initializer, beanFactory, initializer); } } private void addServletContextInitializerBean(Class<?> type, String beanName, ServletContextInitializer initializer, ListableBeanFactory beanFactory, Object source) { //這裡的initializers是個map,按照類型,bean對象進行加載,這裡的type是javax.servlet.Servlet.class,value是上面的DispatcherServletRegistrationBean this.initializers.add(type, initializer); if (source != null) { // Mark the underlying source as seen in case it wraps an existing bean //將DispatcherServlet對應的bean加到這裡 this.seen.add(source); } if (logger.isTraceEnabled()) { String resourceDescription = getResourceDescription(beanName, beanFactory); int order = getOrder(initializer); logger.trace("Added existing " + type.getSimpleName() + " initializer bean '" + beanName + "'; order=" + order + ", resource=" + resourceDescription); } }
再回到ServletContextInitializerBeans的構造方法,接著看後面的
public ServletContextInitializerBeans(ListableBeanFactory beanFactory, Class<? extends ServletContextInitializer>... initializerTypes) { ...... //這裡的內容上面已經看過瞭,我們現在看下面這句,點進去 addAdaptableBeans(beanFactory); 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); }
protected void addAdaptableBeans(ListableBeanFactory beanFactory) { //這句不用關註 MultipartConfigElement multipartConfig = getMultipartConfig(beanFactory); //這句不用關註 addAsRegistrationBean(beanFactory, Servlet.class, new ServletRegistrationBeanAdapter(multipartConfig)); //點到這裡去看看 addAsRegistrationBean(beanFactory, Filter.class, new FilterRegistrationBeanAdapter()); for (Class<?> listenerType : ServletListenerRegistrationBean.getSupportedTypes()) { addAsRegistrationBean(beanFactory, EventListener.class, (Class<EventListener>) listenerType, new ServletListenerRegistrationBeanAdapter()); } }
private <T, B extends T> void addAsRegistrationBean(ListableBeanFactory beanFactory, Class<T> type, Class<B> beanType, RegistrationBeanAdapter<T> adapter) { //這裡的beanType是 Filter.class,下面這句就是從beanFactory中獲取所有類型為Filter.class的bean List<Map.Entry<String, B>> entries = getOrderedBeansOfType(beanFactory, beanType, this.seen); for (Entry<String, B> entry : entries) { String beanName = entry.getKey(); B bean = entry.getValue(); //將bean放置到this.seen裡面 if (this.seen.add(bean)) { // One that we haven't already seen //包裝成RegistrationBean對象 RegistrationBean registration = adapter.createRegistrationBean(beanName, bean, entries.size()); int order = getOrder(bean); registration.setOrder(order); //同樣放置到this.initializers裡面 this.initializers.add(type, registration); if (logger.isTraceEnabled()) { logger.trace("Created " + type.getSimpleName() + " initializer for bean '" + beanName + "'; order=" + order + ", resource=" + getResourceDescription(beanName, beanFactory)); } } } }
再回到上面的addAdaptableBeans方法,看後面的
protected void addAdaptableBeans(ListableBeanFactory beanFactory) { ......//這裡剛才說過瞭 //下面這部分不說瞭,這裡基本和上面一樣,不過處理的類型變成瞭ServletContextAttributeListener.class、ServletRequestListener.class、ServletRequestAttributeListener.class、HttpSessionAttributeListener.class、HttpSessionIdListener.class、HttpSessionListener.class、ServletContextListener.class這些類型 for (Class<?> listenerType : ServletListenerRegistrationBean.getSupportedTypes()) { addAsRegistrationBean(beanFactory, EventListener.class, (Class<EventListener>) listenerType, new ServletListenerRegistrationBeanAdapter()); } }
再回到ServletContextInitializerBeans的構造方法,接著看後面的
public ServletContextInitializerBeans(ListableBeanFactory beanFactory, Class<? extends ServletContextInitializer>... initializerTypes) { ......//這裡剛才都說過瞭,看下面 //這裡就是把上面所有獲取到的相關的bean放置到this.sortedList中,下面我是我本地this.sortedList的截圖 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); }
這裡ServletContextInitializerBeans的構造方法就完成瞭,再回過頭去看看這個類的定義
public class ServletContextInitializerBeans extends AbstractCollection<ServletContextInitializer>
這個類繼承瞭AbstractCollection類,那它就需要實現下面這個抽象方法
public abstract Iterator<E> iterator();
我們看看ServletContextInitializerBeans的iterator的方法
@Override public Iterator<ServletContextInitializer> iterator() { return this.sortedList.iterator(); }
看到瞭吧,這就是返回上面的this.sortedList.iterator()
我們再次回到ServletWebServerApplicationContext的selfInitialize方法
private void selfInitialize(ServletContext servletContext) throws ServletException { ......//這裡上面都說過瞭 //getServletContextInitializerBeans()這個方法就是構造瞭ServletContextInitializerBeans //這裡的for循環也是調用瞭ServletContextInitializerBeans的iterator的方法,實際上遍歷的也就是上面的this.sortedList for (ServletContextInitializer beans : getServletContextInitializerBeans()) { //這裡就是把在beanFactory中查找到的Servlet.class,filter.class,監聽器等等添加到tomcat容器中,我們就隻進到servlet裡面去看看 //進到DispatcherServletRegistrationBean裡面去看看 beans.onStartup(servletContext); } }
//這個方法在DispatcherServletRegistrationBean的父類RegistrationBean中 //所有的Servlet.class,filter.class,監聽器都會走到這裡 public final void onStartup(ServletContext servletContext) throws ServletException { //這裡是返回的表述,不關註 String description = getDescription(); if (!isEnabled()) { logger.info(StringUtils.capitalize(description) + " was not registered (disabled)"); return; } //這裡由不同的子類去實現,DispatcherServletRegistrationBean會調用到ServletRegistrationBean中 register(description, servletContext); }
//這個方法是在ServletRegistrationBean這個類中 @Override protected ServletRegistration.Dynamic addRegistration(String description, ServletContext servletContext) { String name = getServletName(); //這裡的servletContext上面的ApplicationContextFacade的對象,這裡就會將DispatcherServlet的bean對象加載到TomcatEmbeddedContext中,後續所有的http請求最後都會流轉到DispatcherServlet去進行具體的分發 return servletContext.addServlet(name, this.servlet); }
到這裡Servlet.class,filter.class,監聽器就全部加載到tomcat中去
5、創建RequestMappingHandlerMapping
再看看上面的META-INF/spring.factories文件
# Auto Configuration Import Filters org.springframework.boot.autoconfigure.AutoConfigurationImportFilter=\ org.springframework.boot.autoconfigure.condition.OnBeanCondition,\ org.springframework.boot.autoconfigure.condition.OnClassCondition,\ org.springframework.boot.autoconfigure.condition.OnWebApplicationCondition # Auto Configure org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ ...... org.springframework.boot.autoconfigure.web.servlet.DispatcherServletAutoConfiguration,\ org.springframework.boot.autoconfigure.web.servlet.ServletWebServerFactoryAutoConfiguration,\ ...... #現在我們重點來看這個類 org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration,\ ......
具體的加載和上面部分都類似,就不展開瞭,直接看我們需要的
//這裡會創建RequestMappingHandlerMapping的bean @Bean @Primary @Override public RequestMappingHandlerMapping requestMappingHandlerMapping( @Qualifier("mvcContentNegotiationManager") ContentNegotiationManager contentNegotiationManager, @Qualifier("mvcConversionService") FormattingConversionService conversionService, @Qualifier("mvcResourceUrlProvider") ResourceUrlProvider resourceUrlProvider) { // Must be @Primary for MvcUriComponentsBuilder to work return super.requestMappingHandlerMapping(contentNegotiationManager, conversionService, resourceUrlProvider);
看下這個類的繼承圖
RequestMappingHandlerMapping實現瞭InitializingBean接口,會在bean對象創建後的invokeInitMethods方法中調用afterPropertiesSet方法,最終會調用的AbstractHandlerMethodMapping的afterPropertiesSet方法中
@Override public void afterPropertiesSet() { initHandlerMethods(); } /** * Scan beans in the ApplicationContext, detect and register handler methods. * @see #getCandidateBeanNames() * @see #processCandidateBean * @see #handlerMethodsInitialized */ protected void initHandlerMethods() { //這裡查找beanFactory中的所有bean進行遍歷 for (String beanName : getCandidateBeanNames()) { if (!beanName.startsWith(SCOPED_TARGET_NAME_PREFIX)) { //點到這裡去看看 processCandidateBean(beanName); } } handlerMethodsInitialized(getHandlerMethods()); }
protected void processCandidateBean(String beanName) { Class<?> beanType = null; try { //根據beanName獲取對應bean的Class對象 beanType = obtainApplicationContext().getType(beanName); } catch (Throwable ex) { // An unresolvable bean type, probably from a lazy bean - let's ignore it. if (logger.isTraceEnabled()) { logger.trace("Could not resolve type for bean '" + beanName + "'", ex); } } //判斷類上是否有Controller.class,RequestMapping.class註解 if (beanType != null && isHandler(beanType)) { //這裡就會解析beanName上的所有方法進行遍歷,查找有 RequestMapping.class註解的方法,創建RequestMappingInfo對象,放置到registry屬性中(在AbstractHandlerMethodMapping)中,這樣我們所有定義的controller中的http請求就會全部被掃描到 detectHandlerMethods(beanName); } }
6、加載RequestMappingHandlerMapping到DispatcherServlet中
在我們第一次請求的時候,會執行到DispatcherServlet的initStrategies方法,這個方法隻會執行一次
protected void initStrategies(ApplicationContext context) { ...... 這就會加載之前查找到的RequestMappingHandlerMapping中的我們定義的controller initHandlerMappings(context); ...... }
會調用到這裡
private void initHandlerMappings(ApplicationContext context) { this.handlerMappings = null; if (this.detectAllHandlerMappings) { // Find all HandlerMappings in the ApplicationContext, including ancestor contexts. //這裡會在beanFactory中查找所有HandlerMapping.class的bean,其中就包含我們第5部分的RequestMappingHandlerMapping Map<String, HandlerMapping> matchingBeans = BeanFactoryUtils.beansOfTypeIncludingAncestors(context, HandlerMapping.class, true, false); if (!matchingBeans.isEmpty()) { //將所有查找到的放置到handlerMappings中 this.handlerMappings = new ArrayList<>(matchingBeans.values()); // We keep HandlerMappings in sorted order. AnnotationAwareOrderComparator.sort(this.handlerMappings); } } ...... }
當我們瀏覽器請求的時候,最終會走到DispatcherServlet的doDispatch的方法,處理我們的請求並返回,簡單看看
protected void doDispatch(HttpServletRequest request, HttpServletResponse response) throws Exception { ...... try { ModelAndView mv = null; Exception dispatchException = null; try { processedRequest = checkMultipart(request); multipartRequestParsed = (processedRequest != request); // Determine handler for the current request. //在這裡,就會請求request的請求路徑去查找實際要執行的controller的方法,點進去看看 mappedHandler = getHandler(processedRequest); ...... }
@Nullable protected HandlerExecutionChain getHandler(HttpServletRequest request) throws Exception { if (this.handlerMappings != null) { //這其實就是根據遍歷,查找對應的路徑,這個this.handlerMappings就是就是在initHandlerMappings方法中賦值的 for (HandlerMapping mapping : this.handlerMappings) { HandlerExecutionChain handler = mapping.getHandler(request); if (handler != null) { return handler; } } } return null; }
到這裡,springboot 加載web容器的整個流程基本就算完成瞭,這塊涉及的東西比較多,所以說的可能比較粗,大傢見諒。
推薦閱讀:
- 基於spring boot排除掃描類的三種方式小結
- SpringBoot嵌入式Servlet容器與定制化組件超詳細講解
- Spring Boot 中嵌入式 Servlet 容器自動配置原理解析
- Springboot配置suffix指定mvc視圖的後綴方法
- SpringBoot內置tomcat啟動原理詳解