什么时候创建嵌入式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容器