spring boot 載入web容器tomcat流程原始碼分析
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容器的整個流程基本就算完成了,這塊涉及的東西比較多,所以說的可能比較粗,大家見諒。