什么时候创建嵌入式的Servlet容器工厂?什么时候获取嵌入式的Servlet容器并启动Tomcat;
获取嵌入式的Servlet容器工厂:
- springboot应用启动运行run方法
- refreshContext(context):springBoot刷新IOC容器[创建IOC容器对象,并初始化容器,创建容器中的每一个组件];如果是web应用创建web.servlet.context.AnnotationConfigServletWebServerApplicationContext, 否则,创建默认的AnnotationConfigReactiveWebServerApplicationContext;
- refresh(Context)刷新刚才创建的容器.
@Override
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();
}
}
}
- onRefresh(); web的IOC容器重写了onfresh方法.
web ioc容器会创建嵌入式的servlet容器:createWebServer(); - ServletWebServerFactory factory = getWebServerFactory();
- 获取嵌入式的servlet容器工厂,
从ioc容器中获取ServletWebServerFactory组件,TomcatServletWebServerFactory创建对象,后置处理器一看是这个对象,就获取所有的定制器来先定制servlet容器的相关配置 - 使用容器工厂获取嵌入式的servlet容器
- 嵌入式的servlet容器创建对象,并启动servlet容器,
先启动嵌入式的servlet容器,在将ioc容器中剩下的没有创建出的对象获取出来.
ioc容器启动创建嵌入式的servlet容器.