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的部分,為了避免文章知識點過于分散,其他相關(guān)的如bean的加載,tomcat內(nèi)部流程等不做深入討論。
1、在springboot web工程中,全局上下文是AnnotationConfigServletWebApplicationContext
下面的部分,我們具體來看下
首先,我們的入口代碼一般都是這樣寫的
public static void main(String[] args) {
SpringApplication.run(BootargsApplication.class,args);
}
跳轉(zhuǎn)到run方法里面,依次會調(diào)用下面兩個方法
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);
}
首先會創(chuàng)建SpringApplication實例對象,跳轉(zhuǎn)到SpringApplication的構(gòu)造方法去看看,依次會調(diào)用如下方法
public SpringApplication(Class<?>... primarySources) {
this(null, primarySources);
}
@SuppressWarnings({ "unchecked", "rawtypes" })
public SpringApplication(ResourceLoader resourceLoader, Class<?>... primarySources) {
......
//本次不相關(guān)的代碼全部省略掉,只保留相關(guān)代碼
//這里的 this.webApplicationType=WebApplicationType.SERVLET, 我們來分析下這個代碼的具體的執(zhí)行賦值
this.webApplicationType = WebApplicationType.deduceFromClasspath();
......
}
繼續(xù)跳轉(zhuǎn)到WebApplicationType.deduceFromClasspath()去看看
//這個方法主要是在當(dāng)前類路徑下查找指定的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)的調(diào)用來看run方法的代碼
public ConfigurableApplicationContext run(String... args) {
.......
try {
......
//我們來看這個context的創(chuàng)建,context=new AnnotationConfigServletWebServerApplicationContext()下面來具體看這塊的執(zhí)行
context = createApplicationContext();
......
//后續(xù)幾個部分會來說明這個方法
refreshContext(context);
......
}
catch (Throwable ex) {
......
}
try {
.......
}
catch (Throwable ex) {
.......
}
return context;
}
createApplicationContext()依次會調(diào)用如下方法
protected ConfigurableApplicationContext createApplicationContext() {
//這里的this.webApplicationType就是上面的WebApplicationType.SERVLET
return this.applicationContextFactory.create(this.webApplicationType);
}
//最終會調(diào)用到這個lambda表達式,入?yún)⒕褪巧厦娴腤ebApplicationType.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就已經(jīng)創(chuàng)建出來了,這塊代碼也比較簡單。就不多說什么了
2、查找ServletWebServerFactory
再次回到new SpringApplication(primarySources).run(args)的調(diào)用來看run方法的代碼
public ConfigurableApplicationContext run(String... args) {
.......
try {
......
//上面已經(jīng)對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);
}
繼續(xù)點到refresh(context)
protected void refresh(ConfigurableApplicationContext applicationContext) {
//這里的applicationContext就是AnnotationConfigServletWebServerApplicationContext的對象,由于這個類沒有refresh方法,會跳轉(zhuǎn)到它的父類ServletWebServerApplicationContext的方法中去,我們繼續(xù)點進去
applicationContext.refresh();
}
點到ServletWebServerApplicationContext的refresh方法
public final void refresh() throws BeansException, IllegalStateException {
try {
//繼續(xù)跳轉(zhuǎn)到父類AbstractApplicationContext方法
super.refresh();
}
catch (RuntimeException ex) {
WebServer webServer = this.webServer;
if (webServer != null) {
webServer.stop();
}
throw ex;
}
}
打開AbstractApplicationContext的refresh方法
//springboot 大部分的初始化工作是在這里完成的,不過這不是我們本地的重點,不相關(guān)的我們統(tǒng)統(tǒng)略過
public void refresh() throws BeansException, IllegalStateException {
synchronized (this.startupShutdownMonitor) {
......
try {
......
//繼續(xù)點到這個方法,這里又會跳轉(zhuǎn)到ServletWebServerApplicationContext這個類的方法
onRefresh();
.....
}
catch (BeansException ex) {
.....
}
finally {
.....
}
}
}
打開ServletWebServerApplicationContext的onRefresh方法
protected void onRefresh() {
super.onRefresh();
try {
//這里就是我們本次的重點,會在這里創(chuàng)建具體的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) {
//這里只是做個標記,不用關(guān)注,跳過
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的定義,返回對應(yīng)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對象,如果當(dāng)前bean還未創(chuàng)建,則此時就會創(chuàng)建bean對象并返回
return getBeanFactory().getBean(beanNames[0], ServletWebServerFactory.class);
}
從上面的代碼并看不出來實際的ServletWebServerFactory對象具體是什么?下面帶著大家一起簡單過下這部分的加載,這里具體就是springboot 加載bean的流程了,這部分的邏輯比較多,本次就不具體展開。關(guān)于springboot 加載bean的流程計劃后續(xù)專門再寫一篇。
springboot在啟動過程中會在當(dāng)前類路徑下META-INF/spring.factories這個文件中,key=org.springframework.boot.autoconfigure.EnableAutoConfiguration的屬性的作為bean的定義進行加載,在這過程中還會使用key=org.springframework.boot.autoconfigure.AutoConfigurationImportFilterfilter的屬性作為過濾,配合META-INF/spring-autoconfigure-metadata.properties對這些類做一個過濾,剔除掉不符合的類(后續(xù)還會根據(jù)類上的注解判斷是否要繼續(xù)剔除)。
當(dāng)前這些主要在spring-boot-autoconfigure-2.5.1.jar這個文件中

下面截取上面說的兩部分,可以看到這里的過濾器就3個,具體不展開討論了,自動導(dǎo)入的類就是下面的再加過濾去掉的
# 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=\ ...... #下面這個會在創(chuàng)建servelt中使用,下部分我們再關(guān)注它 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注解,會繼續(xù)導(dǎo)入這幾個類,
ServletWebServerFactoryConfiguration.EmbeddedTomcat.class, ServletWebServerFactoryConfiguration.EmbeddedJetty.class, ServletWebServerFactoryConfiguration.EmbeddedUndertow.class
這三個都是本次相關(guān)的,它們都是ServletWebServerFactoryConfiguration的內(nèi)部類,我們進去看看,類的結(jié)構(gòu)都是一樣的,我們就看下ServletWebServerFactoryConfiguration.EmbeddedTomcat類吧

可以看到EmbeddedTomcat上面有ConditionalOnClass,ConditionalOnMissingBean這兩個注解,
簡單說下,ConditionalOnClass是表示當(dāng)前類路徑下存在對應(yīng)類是加載
ConditionalOnMissingBean是表示當(dāng)前beanFactory中沒有對應(yīng)類型bean定義的話加載
多個條件都是and的關(guān)系,有一個條件不成立,就不會去進行后續(xù)處理。
在這里EmbeddedTomcat類這兩個條件是成立的,這時就會繼續(xù)遍歷當(dāng)前類的所有方法,找到@Bean注解的方法,加載到beanFactory中去
而EmbeddedJetty,EmbeddedUndertow兩個類條件是不成立的,就不會進行后續(xù)執(zhí)行,剔除掉了


這里就會把EmbeddedTomcat.tomcatServletWebServerFactory這個方法進行加載,返回值是TomcatServletWebServerFactory類型,我們看下TomcatServletWebServerFactory類的繼承圖,可以看到它正好是繼承了ServletWebServerFactory接口。

再次打開ServletWebServerApplicationContext的getWebServerFactory方法
protected ServletWebServerFactory getWebServerFactory() {
.......
//所以這里的邏輯實際上會執(zhí)行ServletWebServerFactoryConfiguration.EmbeddedTomcat類的tomcatServletWebServerFactory方法,返回TomcatServletWebServerFactory對象,相關(guān)的屬性注入等等這里就不講述了
return getBeanFactory().getBean(beanNames[0], ServletWebServerFactory.class);
}
到這里,整個ServletWebServerFactory的查找就完成了
3、創(chuàng)建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=\ ...... #現(xiàn)在我們重點來看這個類 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)
//我們當(dāng)前只關(guān)注這ConditionalOnWebApplication、ConditionalOnClass注解
//ConditionalOnWebApplication是根據(jù)type來判斷指定類是否存在
//當(dāng)前的type是 Type.SERVLET,是來查找org.springframework.web.context.support.GenericWebApplicationContext類是否存在,這個類存在于spring-web中,所以這個條件是true
@ConditionalOnWebApplication(type = Type.SERVLET)
//這個注解上面說過了 ,就是查找指定的類是否存在,這個是查找DispatcherServlet.class是否存在,這里也會返回true
@ConditionalOnClass(DispatcherServlet.class)
//上面兩個條件都成立,就會執(zhí)行后續(xù)的操作,去遍歷內(nèi)部類和方法
@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)
//這里還是個條件,通過實現(xiàn)Condition接口,通過matches方法來判斷
//DefaultDispatcherServletCondition這個類就在當(dāng)前這個文件里,matches判斷的結(jié)果也是true
@Conditional(DefaultDispatcherServletCondition.class)
//ServletRegistration.class這個類存在于tomcat-embed-core里面,這個結(jié)果也是true
@ConditionalOnClass(ServletRegistration.class)
//上面兩個條件成立,就會執(zhí)行后續(xù)的操作,去遍歷內(nèi)部類和方法
@EnableConfigurationProperties(WebMvcProperties.class)
protected static class DispatcherServletConfiguration {
//beanFactory會創(chuàng)建這個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,并執(zhí)行加載bean定義的流程,這就是上面的類了
@Import(DispatcherServletConfiguration.class)
protected static class DispatcherServletRegistrationConfiguration {
@Bean(name = DEFAULT_DISPATCHER_SERVLET_REGISTRATION_BEAN_NAME)
//ConditionalOnBean查找是否存在指定bean的定義,這個方法要注入?yún)?shù),需要這個類,當(dāng)前這里就是上面的dispatcherServlet方法定義的,這里也是存在的
@ConditionalOnBean(value = DispatcherServlet.class, name = DEFAULT_DISPATCHER_SERVLET_BEAN_NAME)
//DispatcherServlet dispatcherServlet這個就是dispatcherServlet這個方法定義的bean,在創(chuàng)建DispatcherServletRegistrationBean這個bean的時候,就會去查找dispatcherServlet是否存在,如果不存在,先創(chuàng)建dispatcherServlet這個bean,再創(chuàng)建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;
}
}
......
}
上面就是創(chuàng)建DispatcherServlet,DispatcherServletRegistrationBean的過程了
4、創(chuàng)建tomcat,加載Servlet.class,filter.class,監(jiān)聽器
再次回到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");
//上面我們已經(jīng)看到了這里,factory是TomcatServletWebServerFactory類的一個實例對象
ServletWebServerFactory factory = getWebServerFactory();
//這里還是做個標記,不用關(guān)注
createWebServer.tag("factory", factory.getClass().toString());
//這里就是具體創(chuàng)建tomcat了,這里的入?yún)etSelfInitializer()是個lambda表達式,這個后續(xù)很重要
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;
}
//是創(chuàng)建webServer的參數(shù)
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())會調(diào)用到TomcatServletWebServerFactory的getWebServer的方法
public WebServer getWebServer(ServletContextInitializer... initializers) {
.......
//上面的入?yún)谶@里傳下去
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);
//繼續(xù)傳下去
configureContext(context, initializersToUse);
postProcessContext(context);
}
再點到configureContext(context, initializersToUse)這個調(diào)用去看看
protected void configureContext(Context context, ServletContextInitializer[] initializers) {
//會傳遞給TomcatStarter,作為構(gòu)造參數(shù),下面我們?nèi)ミ@里看看
TomcatStarter starter = new TomcatStarter(initializers);
......
}
下面我們?nèi)タ纯碩omcatStarter這個類是怎么使用這個initializers這個構(gòu)造參數(shù)的。
這個類不長
class TomcatStarter implements ServletContainerInitializer {
......
TomcatStarter(ServletContextInitializer[] initializers) {
//入?yún)鳛樗某蓡T屬性
this.initializers = initializers;
}
@Override
public void onStartup(Set<Class<?>> classes, ServletContext servletContext) throws ServletException {
try {
for (ServletContextInitializer initializer : this.initializers) {
//會在這里調(diào)用onStartup方法,這里的入?yún)⒕褪茿pplicationContextFacade的對象,里面包裝了ApplicationContext,里面再包裝了TomcatEmbeddedContext,這要就和tomcat聯(lián)系起來了,下面的截圖就是servletContext的對象結(jié)構(gòu)
initializer.onStartup(servletContext);
}
}
catch (Exception ex) {
......
}

上面的initializer.onStartup(servletContext)會調(diào)用到ServletWebServerApplicationContext的selfInitialize方法
private void selfInitialize(ServletContext servletContext) throws ServletException {
//這里是將ApplicationContextFacade設(shè)置到當(dāng)前的servletContext上
prepareWebApplicationContext(servletContext);
//這里是在beanFactory中注冊application的scope
registerApplicationScope(servletContext);
//這里還是注冊上下文相關(guān)的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這個參數(shù),所以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對應(yīng)的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對應(yīng)的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對應(yīng)的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的構(gòu)造方法,接著看后面的
public ServletContextInitializerBeans(ListableBeanFactory beanFactory,
Class<? extends ServletContextInitializer>... initializerTypes) {
...... //這里的內(nèi)容上面已經(jīng)看過了,我們現(xiàn)在看下面這句,點進去
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) {
//這句不用關(guān)注
MultipartConfigElement multipartConfig = getMultipartConfig(beanFactory);
//這句不用關(guān)注
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的構(gòu)造方法,接著看后面的
public ServletContextInitializerBeans(ListableBeanFactory beanFactory,
Class<? extends ServletContextInitializer>... initializerTypes) {
......//這里剛才都說過了,看下面
//這里就是把上面所有獲取到的相關(guān)的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的構(gòu)造方法就完成了,再回過頭去看看這個類的定義
public class ServletContextInitializerBeans extends AbstractCollection<ServletContextInitializer>
這個類繼承了AbstractCollection類,那它就需要實現(xiàn)下面這個抽象方法
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()這個方法就是構(gòu)造了ServletContextInitializerBeans
//這里的for循環(huán)也是調(diào)用了ServletContextInitializerBeans的iterator的方法,實際上遍歷的也就是上面的this.sortedList
for (ServletContextInitializer beans : getServletContextInitializerBeans()) {
//這里就是把在beanFactory中查找到的Servlet.class,filter.class,監(jiān)聽器等等添加到tomcat容器中,我們就只進到servlet里面去看看
//進到DispatcherServletRegistrationBean里面去看看
beans.onStartup(servletContext);
}
}
//這個方法在DispatcherServletRegistrationBean的父類RegistrationBean中
//所有的Servlet.class,filter.class,監(jiān)聽器都會走到這里
public final void onStartup(ServletContext servletContext) throws ServletException {
//這里是返回的表述,不關(guān)注
String description = getDescription();
if (!isEnabled()) {
logger.info(StringUtils.capitalize(description) + " was not registered (disabled)");
return;
}
//這里由不同的子類去實現(xiàn),DispatcherServletRegistrationBean會調(diào)用到ServletRegistrationBean中
register(description, servletContext);
}
//這個方法是在ServletRegistrationBean這個類中
@Override
protected ServletRegistration.Dynamic addRegistration(String description, ServletContext servletContext) {
String name = getServletName();
//這里的servletContext上面的ApplicationContextFacade的對象,這里就會將DispatcherServlet的bean對象加載到TomcatEmbeddedContext中,后續(xù)所有的http請求最后都會流轉(zhuǎn)到DispatcherServlet去進行具體的分發(fā)
return servletContext.addServlet(name, this.servlet);
}
到這里Servlet.class,filter.class,監(jiān)聽器就全部加載到tomcat中去
5、創(chuàng)建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,\ ...... #現(xiàn)在我們重點來看這個類 org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration,\ ......
具體的加載和上面部分都類似,就不展開了,直接看我們需要的
//這里會創(chuàng)建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實現(xiàn)了InitializingBean接口,會在bean對象創(chuàng)建后的invokeInitMethods方法中調(diào)用afterPropertiesSet方法,最終會調(diào)用的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 {
//根據(jù)beanName獲取對應(yīng)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注解的方法,創(chuàng)建RequestMappingInfo對象,放置到registry屬性中(在AbstractHandlerMethodMapping)中,這樣我們所有定義的controller中的http請求就會全部被掃描到
detectHandlerMethods(beanName);
}
}
6、加載RequestMappingHandlerMapping到DispatcherServlet中
在我們第一次請求的時候,會執(zhí)行到DispatcherServlet的initStrategies方法,這個方法只會執(zhí)行一次
protected void initStrategies(ApplicationContext context) {
......
這就會加載之前查找到的RequestMappingHandlerMapping中的我們定義的controller
initHandlerMappings(context);
......
}
會調(diào)用到這里
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);
}
}
......
}
當(dāng)我們?yōu)g覽器請求的時候,最終會走到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的請求路徑去查找實際要執(zhí)行的controller的方法,點進去看看
mappedHandler = getHandler(processedRequest);
......
}
@Nullable
protected HandlerExecutionChain getHandler(HttpServletRequest request) throws Exception {
if (this.handlerMappings != null) {
//這其實就是根據(jù)遍歷,查找對應(yīng)的路徑,這個this.handlerMappings就是就是在initHandlerMappings方法中賦值的
for (HandlerMapping mapping : this.handlerMappings) {
HandlerExecutionChain handler = mapping.getHandler(request);
if (handler != null) {
return handler;
}
}
}
return null;
}
到這里,springboot 加載web容器的整個流程基本就算完成了,這塊涉及的東西比較多,所以說的可能比較粗,大家見諒。
相關(guān)文章
Springmvc調(diào)用存儲過程,并返回存儲過程返還的數(shù)據(jù)方式
這篇文章主要介紹了Springmvc調(diào)用存儲過程,并返回存儲過程返還的數(shù)據(jù)方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-11-11
SpringMVC JSON數(shù)據(jù)交互及RESTful支持實現(xiàn)方法
這篇文章主要介紹了SpringMVC JSON數(shù)據(jù)交互及RESTful支持實現(xiàn)方法,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-06-06
SpringBoot AOP方式實現(xiàn)多數(shù)據(jù)源切換的方法
本篇文章主要介紹了SpringBoot AOP方式實現(xiàn)多數(shù)據(jù)源切換的方法,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-03-03
Java編程實現(xiàn)中英混合字符串?dāng)?shù)組按首字母排序的方法
這篇文章主要介紹了Java編程實現(xiàn)中英混合字符串?dāng)?shù)組按首字母排序的方法,涉及Java字符串操作及拼音轉(zhuǎn)換的相關(guān)使用技巧,具有一定參考借鑒價值,需要的朋友可以參考下2015-11-11
mybatis的insert插入后獲取自增id的方法詳解(從controller到mapper)
這篇文章主要介紹了mybatis的insert插入后獲取自增id的示例代碼,本文給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-10-10

