SpringBoot启动源码解析,本文基于spring-boot:2.1.12版本分析。
SpringBoot启动过程源码解析
SpringBoot启动准备工作
从SpringBoot工程的main()方法进入SpringApplication.run()方法,注意此处的run()方法是一个静态方法。
@SpringBootApplication
public class MySpringServerApp {
public static void main(String[] args) {
SpringApplication.run(EurekaServerApp.class, args);
}
}
依次进入下面的方法:
/**
* 这是一个静态启动帮助类,可以使用默认的资源配置运行一个SpringApplication
*
* @param primarySource the primary source to load
* @param args the application arguments (usually passed from a Java main method)
* @return the running {@link ApplicationContext}
*/
public static ConfigurableApplicationContext run(Class<?> primarySource, String... args) {
return run(new Class<?>[] { primarySource }, args);
}
/**
* 这是一个静态启动帮助类,可以使用默认的资源配置和用户提供的参数运行一个SpringApplication
* @param primarySources the primary sources to load
* @param args the application arguments (usually passed from a Java main method)
* @return the running {@link ApplicationContext}
*/
public static ConfigurableApplicationContext run(Class<?>[] primarySources, String[] args) {
return new SpringApplication(primarySources).run(args);
}
继续进入new SpringApplication(primarySources)分析这个构造函数
/**
* 创建一个新的SpringApplication实例。
应用程序上下文将从指定的主源文档加载bean以获取详细信息。
可以在调用run之前自定义实例
* @param resourceLoader the resource loader to use
* @param primarySources the primary bean sources
* @see #run(Class, String[])
* @see #setSources(Set)
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
public SpringApplication(ResourceLoader resourceLoader, Class<?>... primarySources) {
this.resourceLoader = resourceLoader;
Assert.notNull(primarySources, "PrimarySources must not be null");
this.primarySources = new LinkedHashSet<>(Arrays.asList(primarySources));
this.webApplicationType = WebApplicationType.deduceFromClasspath();
// 设置初始化器,加载spring.factories配置中的org.springframework.context.ApplicationContextInitializer
setInitializers((Collection) getSpringFactoriesInstances(ApplicationContextInitializer.class));
// 设置监听器,加载spring.factories配置中的org.springframework.context.ApplicationListener
setListeners((Collection) getSpringFactoriesInstances(ApplicationListener.class));
this.mainApplicationClass = deduceMainApplicationClass();
}
这里的源码,我们主要分析如果设置初始化器和设置监听器,对应着spring.factories配置文件中的org.springframework.context.ApplicationContextInitializer和org.springframework.context.ApplicationListener配置项,如下图:
ApplicationContextInitializer是spring组件spring-context组件中的一个接口,主要是spring ioc容器刷新之前的一个回调接口,用于处于自定义逻辑。
ApplicationListener监听器会贯穿springBoot整个生命周期。
SpringBoot启动过程
通过SpringApplication类中非静态的run方法源码解析,该方法作用是:运行一个Spring的application,创建并刷新新的ApplicationContext。
public ConfigurableApplicationContext run(String... args) {
StopWatch stopWatch = new StopWatch();
stopWatch.start();
ConfigurableApplicationContext context = null;
Collection<SpringBootExceptionReporter> exceptionReporters = new ArrayList<>();
//设置java.awt.headless属性,是J2SE的一种模式用于展示系统配置,
//很多监控工具如jconsole 需要将该值设置为true,系统变量默认为true
configureHeadlessProperty();
// 1、获取监听器,获取spring.factories中的SpringApplicationRunListener
SpringApplicationRunListeners listeners = getRunListeners(args);
// 2、启动监听器
listeners.starting();
try {
// 3、构造容器环境
ApplicationArguments applicationArguments = new DefaultApplicationArguments(args);
ConfigurableEnvironment environment = prepareEnvironment(listeners, applicationArguments);
//设置需要忽略的bean
configureIgnoreBeanInfo(environment);
// 打印spring bannner
Banner printedBanner = printBanner(environment);
// 4、创建容器
// 用于创建ApplicationContext的策略方法。
// 默认情况下,在返回到适当的默认值之前,此方法将遵从任何显式设置的应用程序上下文或应用程序上下文类。
context = createApplicationContext();
// 5、实例化SpringBootExceptionReporter.class,用来支持报告关于启动的错误
exceptionReporters = getSpringFactoriesInstances(SpringBootExceptionReporter.class,
new Class[] { ConfigurableApplicationContext.class }, context);
// 6、准备容器上下文
prepareContext(context, environment, listeners, applicationArguments, printedBanner);
// 7、刷新容器上下文,此处会一直调到spring IOC容器的refresh()方法。
refreshContext(context);
// 8、在刷新上下文后调用,本方法默认留空,为可扩展方法,用户可以扩展
afterRefresh(context, applicationArguments);
stopWatch.stop();
if (this.logStartupInfo) {
new StartupInfoLogger(this.mainApplicationClass).logStarted(getApplicationLog(), stopWatch);
}
listeners.started(context);
callRunners(context, applicationArguments);
}
catch (Throwable ex) {
handleRunFailure(context, ex, exceptionReporters, listeners);
throw new IllegalStateException(ex);
}
try {
listeners.running(context);
}
catch (Throwable ex) {
handleRunFailure(context, ex, exceptionReporters, null);
throw new IllegalStateException(ex);
}
return context;
}
refreshContext()源码解析
private void refreshContext(ConfigurableApplicationContext context) {
refresh(context);
if (this.registerShutdownHook) {
try {
context.registerShutdownHook();
}
catch (AccessControlException ex) {
// Not allowed in some environments.
}
}
}
/**
* 刷新当前的应用上下文
* @param applicationContext the application context to refresh
*/
protected void refresh(ApplicationContext applicationContext) {
Assert.isInstanceOf(AbstractApplicationContext.class, applicationContext);
// 调用spring IOC核心方法refresh();
((AbstractApplicationContext) applicationContext).refresh();
}