SpringBoot的启动流程可以分为几大部分: 1.创建SpringApplication,加载监听器 2.启动监听器 3.创建创建环境 4.创建容器 5.将环境放入容器中 6.refresh容器 7.启动所有监听器 创建SpringApplication 构建好SpringApplication执行run() 这里是启动的伪代码
public ConfigurableApplicationContext run(String... args) {
long startTime = System.nanoTime();
DefaultBootstrapContext bootstrapContext = createBootstrapContext();
ConfigurableApplicationContext context = null;
configureHeadlessProperty();
Class<?>[] types = new Class<?>[]{SpringApplication.class, String[].class};
SpringApplicationRunListeners listeners = new SpringApplicationRunListeners(logger,
getSpringFactoriesInstances(SpringApplicationRunListener.class, types, this, args),
this.applicationStartup);
listeners.starting(doWithListeners("spring.boot.application.starting", (listener) -> listener.starting(bootstrapContext),
(step) -> {
if (mainApplicationClass != null) {
step.tag("mainApplicationClass", mainApplicationClass.getName());
}
}));
try {
ApplicationArguments applicationArguments = new DefaultApplicationArguments(args);
ConfigurableEnvironment environment = null;
if (this.environment != null) {
environment = this.environment;
}
switch (this.webApplicationType) {
case SERVLET:
environment = new ApplicationServletEnvironment();
case REACTIVE:
environment = new ApplicationReactiveWebEnvironment();
default:
environment = new ApplicationEnvironment();
}
if (this.addConversionService) {
environment.setConversionService(new ApplicationConversionService());
}
configurePropertySources(environment, args);
configureProfiles(environment, args);
listeners.environmentPrepared(bootstrapContext, environment);
bindToSpringApplication(environment);
configureIgnoreBeanInfo(environment);
Banner printedBanner = printBanner(environment);
context = new AnnotationConfigServletWebServerApplicationContext();
this.reader = new AnnotatedBeanDefinitionReader(this);
this.scanner = new ClassPathBeanDefinitionScanner(this);
context.setApplicationStartup(this.applicationStartup);
prepareContext(bootstrapContext, context, environment, listeners, applicationArguments, printedBanner);
refreshContext(context);
afterRefresh(context, applicationArguments);
Duration timeTakenToStartup = Duration.ofNanos(System.nanoTime() - startTime);
if (this.logStartupInfo) {
new StartupInfoLogger(this.mainApplicationClass).logStarted(getApplicationLog(), timeTakenToStartup);
}
listeners.started(context, timeTakenToStartup);
callRunners(context, applicationArguments);
} catch (Throwable ex) {
handleRunFailure(context, ex, listeners);
throw new IllegalStateException(ex);
}
try {
Duration timeTakenToReady = Duration.ofNanos(System.nanoTime() - startTime);
listeners.ready(context, timeTakenToReady);
} catch (Throwable ex) {
handleRunFailure(context, ex, null);
throw new IllegalStateException(ex);
}
return context;
}
|