Spring boot 启动流程和原理
<!--spring boot 启动类在main 方法中调用run 方法 ,并传入启动类名和args参数 此处 启动类名称被封装进数组 ,进行本地的 run 方法调用. -->
// 1.
org.springframework.boot.SpringApplication.run(java.lang.Object, java.lang.String...) {
return run(new Object[] { source }, args);
}
// 2.
org.springframework.boot.SpringApplication
public static ConfigurableApplicationContext run(java.lang.Object[], java.lang.String[]) {
return new SpringApplication(sources).run(args);
}
// 3.
<!-- 在创建 SpringApplication实例的无参构造器 中会调用当前类的初始化方法 -->
private void initialize(Object[] sources) {
if (sources != null && sources.length > 0) {
this.sources.addAll(Arrays.asList(sources));
}
this.webEnvironment = deduceWebEnvironment();
setInitializers((Collection) getSpringFactoriesInstances(
ApplicationContextInitializer.class));
setListeners((Collection) getSpringFactoriesInstances(ApplicationListener.class));
this.mainApplicationClass = deduceMainApplicationClass();
}
<!-- 在SpringApplication实例创建完成后 ,会调用该实例的对象run ()方法 ,
此时 才会 创建并刷新一个新应用程序 -->
public ConfigurableApplicationContext run(String... args) {
//创建启动计时器
StopWatch stopWatch = new StopWatch();
stopWatch.start();
ConfigurableApplicationContext context = null;
FailureAnalyzers analyzers = null;
//获取系统配置项
configureHeadlessProperty();
//获取spring 监听程序 ,并启动监听器
SpringApplicationRunListeners listeners = getRunListeners(args);
listeners.starting();
try {
ApplicationArguments applicationArguments = new DefaultApplicationArguments(
args);
// 获取环境配置参数
ConfigurableEnvironment environment = prepareEnvironment(listeners,
applicationArguments);
// 输出经典的 spring boot Banner
Banner printedBanner = printBanner(environment);
// 创建环境上下文
context = createApplicationContext();
// 创建失败分析器
analyzers = new FailureAnalyzers(context);
// 对上下文进行刷新前准备前置工作
prepareContext(context, environment, listeners, applicationArguments,
printedBanner);
// 进行容器刷新操作 详见: Spring 容器刷新操作流程
refreshContext(context);
// 在刷新上下文后调用
afterRefresh(context, applicationArguments);
listeners.finished(context, null);
//停止计数器
stopWatch.stop();
if (this.logStartupInfo) {
new StartupInfoLogger(this.mainApplicationClass)
.logStarted(getApplicationLog(), stopWatch);
}
return context;
}
catch (Throwable ex) {
handleRunFailure(context, listeners, analyzers, ex);
throw new IllegalStateException(ex);
}
}
Spring 容器刷新操作流程
<!-- 执行的对象的 refreshContext() 方法 ,内部调用refresh方法 -->
org.springframework.boot.SpringApplication#refreshContext
private void refreshContext(ConfigurableApplicationContext context) {
refresh(context);
if (this.registerShutdownHook) {
try {
context.registerShutdownHook();
}
catch (AccessControlException ex) {
// Not allowed in some environments.
}
}
}
protected void refresh(ApplicationContext applicationContext) {
Assert.isInstanceOf(AbstractApplicationContext.class, applicationContext);
((AbstractApplicationContext) applicationContext).refresh();
}
<!--溯源最终调用的是 AbstractApplicationContext.class 的 refresh 接口-->
org.springframework.context.support.AbstractApplicationContext#refresh
AbstractApplicationContext.class 的 refresh() 方法
public void refresh() throws BeansException, IllegalStateException {
synchronized (this.startupShutdownMonitor) {
// Prepare this context for refreshing.
// 准备好刷新上下文
prepareRefresh();
// Tell the subclass to refresh the internal bean factory.
// 告诉子类刷新内部bean工厂。
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
// Prepare the bean factory for use in this context.
//准备bean工厂,以便在此上下文中使用。
prepareBeanFactory(beanFactory);
try {
// Allows post-processing of the bean factory in context subclasses.
//允许在上下文子类中对bean工厂进行后处理。
postProcessBeanFactory(beanFactory);
// Invoke factory processors registered as beans in the context.
// 调用上下文中注册为bean的工厂处理器
invokeBeanFactoryPostProcessors(beanFactory);
// Register bean processors that intercept bean creation.
// 注册拦截bean创建的bean处理器。
registerBeanPostProcessors(beanFactory);
// Initialize message source for this context.
// 初始化此上下文的消息源。
initMessageSource();
// Initialize event multicaster for this context.
// 初始化此上下文的事件多播程序。
initApplicationEventMulticaster();
// Initialize other special beans in specific context subclasses.
// 初始化特定上下文子类中的其他特殊bean。
onRefresh();
// Check for listener beans and register them.
// 检查侦听器bean并注册它们。
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...
// 重置Spring核心中的公共自省缓存,因为我们可能再也不需要单例bean的元数据了……
resetCommonCaches();
}
}
}