我们知道spring boot项目启动,只需要启动@SpringBootApplication.calss中的含有SpringApplication.run()方法的main方法就可以
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
我们下面来看看Spring Boot应用是怎么启动的。
SpringApplication的启动流程
SpringApplication的启动过程非常复杂,下面是在调用SpringApplication.run方法之后启动的关键动作:
既然要了解原理,最直接的方式当然是看源码:
SpringApplication.class
public ConfigurableApplicationContext run(String... args) {
StopWatch stopWatch = new StopWatch();
stopWatch.start();
ConfigurableApplicationContext context = null;
Collection<SpringBootExceptionReporter> exceptionReporters = new ArrayList();
this.configureHeadlessProperty();
//初始化监听器
SpringApplicationRunListeners listeners = this.getRunListeners(args);
//发布ApplicationStartingEvent
listeners.starting();
try {
//装配参数和环境
ApplicationArguments applicationArguments = new DefaultApplicationArguments(args);
//发布ApplicationEnvironmentPreparedEvent
ConfigurableEnvironment environment = this.prepareEnvironment(listeners, applicationArguments);
this.configureIgnoreBeanInfo(environment);
Banner printedBanner = this.printBanner(environment);
//创建ApplicationContext,并装配
context = this.createApplicationContext();
this.getSpringFactoriesInstances(SpringBootExceptionReporter.class, new Class[]{ConfigurableApplicationContext.class}, context);
//发布ApplicationPreparedEvent
this.prepareContext(context, environment, listeners, applicationArguments, printedBanner);
this.refreshContext(context);
this.afterRefresh(context, applicationArguments);
stopWatch.stop();
if (this.logStartupInfo) {
(new StartupInfoLogger(this.mainApplicationClass)).logStarted(this.getApplicationLog(), stopWatch);
}
//发布ApplicationStartedEvent
listeners.started(context);
//执行Spring中@Bean下的一些操作,如静态方法等
this.callRunners(context, applicationArguments);
} catch (Throwable var9) {
this.handleRunFailure(context, listeners, exceptionReporters, var9);
throw new IllegalStateException(var9);
}
//发布ApplicationReadyEvent
listeners.running(context);
return context;
}