一、Spring Boot 应用启动
一个 Spring Boot 应用的启动通常如下:
@SpringBootApplication
@Slf4j
public class ApplicationMain {
public static void main(String[] args) {
ConfigurableApplicationContext ctx = SpringApplication.run(ApplicationMain.class, args);
}
}
执行如上代码,Spring Boot 程序启动成功。事实上启动 Spring Boot 应用离不开 SpringApplication。 所以,我们跟随 SpringApplication 的脚步,开始从源码角度分析 Spring Boot 的初始化过程。
文档有一句话说了 SpringApplication 做了什么(目的):
Create an appropriate ApplicationContext instance (depending on your classpath)
Register a CommandLinePropertySource to expose command line arguments as Spring properties
Refresh the application context, loading all singleton beans
Trigger any CommandLineRunner beans
二、SpringApplication 构造函数
启动代码先创建 SpringApplication 示例,在执行 run 方法:
public static ConfigurableApplicationContext run(Class<?>[] primarySources, String[] args) {
return new SpringApplication(primarySources).run(args);
}
如下是 SpringApplication 的构造函数代码分析。
this.resourceLoader = resourceLoader;
Assert.notNull(primarySources, "PrimarySources must not be null");
this.primarySources = new LinkedHashSet<>(Arrays.asList(primarySources));
//通过 Classloader 探测不同 web 应用核心类是否存在,进而设置 web 应用类型
.webApplicationType = WebApplicationType.deduceFromClasspath();
setInitializers((Collection)getSpringFactoriesInstances(ApplicationContextInitializer.class));
setListeners((Collection)getSpringFactoriesInstances(ApplicationListener.class));
.mainApplicationClass = deduceMainApplicationClass();


