我们以上图举例,这是最常见的启动方式
进入run方法我们可以看到如下图所示
注释的意思是可以使用默认设置运行ApplicationContext,进入下一层run方法
其中红色框是进行加载初始化配置和准备工作,之后在进入绿色框我们可以看到如下:
在这里获取监听器、加载参数和环境,创建application上下文等工作。
注意绿色框,refreshContext一直点refresh进去点进去后如下:
@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();
}
}
}
每个方法上都有注释可以自己翻译一下,这里就不做过多的介绍,重点关注 finishRefresh()这个方法,点进去,然后ctrl+鼠标左键如下:
这里就是web启动的地方,所以整个过程到这里就结束了。
我将application启动大致分为三个部分:
- 准备阶段:这一阶段进行加载初始化配置和准备工作,也就是我们看到的run()方法。
- 创建上下文阶段:这一阶段进行加载配置信息、bean、各种组件等,即springboot的自动配置原理。
- 启动阶段:这一阶段就是我们看到的refresh()方法,启动各种任务,包括tomcat启动、应用程序和组件的启动。
作为一个初入行业的新人, 欢迎大家指正!!!也希望能够和大家一起进步。