什麼時候創建嵌入式Servlet容器工廠?什麼時候獲取嵌入式的Servlet容器並啓動Tomcat?
獲取嵌入式的Servlet容器工廠
1:SpringBoot應用啓動run方法
2:refreshContext(context);SpringBoot刷新IOC容器,初始化IOC容器
此時需要進行一個判斷:如果是web應用則創建
AnnotationConfigEmbeddedWebApplicationContext容器,如果不是web應用則創建AnnotationConfigApplicationContext容器
3:刷新初始化IOC容器主要步驟
public void refresh() throws BeansException, IllegalStateException {
synchronized (this.startupShutdownMonitor) {
// Prepare this context for refreshing.
prepareRefresh();
// Tell the subclass to refresh the internal bean factory.
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
// Prepare the bean factory for use in this context.
prepareBeanFactory(beanFactory);
try {
// Allows post-processing of the bean factory in context subclasses.
postProcessBeanFactory(beanFactory);
// Invoke factory processors registered as beans in the context.
invokeBeanFactoryPostProcessors(beanFactory);
// Register bean processors that intercept bean creation.
registerBeanPostProcessors(beanFactory);
// Initialize message source for this context.
initMessageSource();
// Initialize event multicaster for this context.
initApplicationEventMulticaster();
// Initialize other special beans in specific context subclasses.
onRefresh();
// Check for listener beans and register them.
registerListeners();
// Instantiate all remaining (non-lazy-init) singletons.
finishBeanFactoryInitialization(beanFactory);
// Last step: publish corresponding event.
finishRefresh();
}
catch (BeansException ex) {
if (logger.isWarnEnabled()) {
logger.warn("Exception encountered during context initialization - " +
"cancelling refresh attempt: " + ex);
}
// Destroy already created singletons to avoid dangling resources.
destroyBeans();
// Reset 'active' flag.
cancelRefresh(ex);
// Propagate exception to caller.
throw ex;
}
finally {
// Reset common introspection caches in Spring's core, since we
// might not ever need metadata for singleton beans anymore...
resetCommonCaches();
}
}
}
4:onRefresh(),web的IOC容器重寫了onRefresh方法
5:web的IOC容器會創建嵌入式的Servlet
(org.springframework.boot.context.embedded.EmbeddedWebApplicationContext#createEmbeddedServletContainer())
6:獲取嵌入式的Servlet容器工廠,從IOC容器中獲取
EmbeddedServletContainerFactory組件,EmbeddedServletContainerFactory創建對象,後置處理器處理這個對象,就獲取所有的定製器來定製Servlet容器的相關配置
7:現在已經獲取到了容器工廠,如下就通過容器工廠獲取嵌入式的Servlet容器(tomcat)
8:先啓動嵌入式的Servlet容器,再將IOC容器中剩下沒有創建出的對象取出來,IOC容器啓動嵌入式的Servlet容器