Springboot启动流程(2.0.1.RELEASE版本为例)
首先贴一段springboot程序的启动代码
@EnableScheduling
@SpringBootApplication(exclude = {QuartzAutoConfiguration.class, DruidDataSourceAutoConfigure.class, DataSourceAutoConfiguration.class, DataSourceHealthIndicatorAutoConfiguration.class
})
public class RedisConnectApplication {
public static void main(final String[] args) {
SpringApplication.run(RedisConnectApplication.class);
}
}
通过以上代码可以看到工程是通过main方法中的SpringApplication.run(RedisConnectApplication.class)开始的
进入run()方法可以看到此方法的作用是通过传入的类对象生成一个ConfigurableApplicationContext实例,ConfigurableApplicationContext这个类很明显的是Application的实现类.
public static ConfigurableApplicationContext run(Class<?>[] primarySources,
String[] args) {
return new SpringApplication(primarySources).run(args);
}
进一步查看new SpringApplication(primarySources).run(args),首先可以看到通过SpringApplication的构造方法创建了一个SpringApplication实例,然后这个实例开始执行了SpringApplication类中的run方法。
探究一下SpringApplication的构造方法进行了哪些操作
/**
*
* 创建一个SpringApplication的实例, 这个application context 将从特定的资源中加载bean
* The instance can be customized before calling {@link #run(String...)}.
*
*/
@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 = deduceWebApplicationType();
setInitializers((Collection) getSpringFactoriesInstances(
ApplicationContextInitializer.class));
setListeners((Collection) getSpringFactoriesInstances(ApplicationListener.class));
this.mainApplicationClass = deduceMainApplicationClass();
}
this.resourceLoader = resourceLoader;设置资源加载器this.primarySources = new LinkedHashSet<>(Arrays.asList(primarySources));设置主源,可以看到primarySources是一个Set集合可以设置多个primarySourcethis.webApplicationType = deduceWebApplicationType();通过环境变量获取webApplicationType,webApplicationType是一个枚举类型,分别为NONE,SERVLET,REACTIVEsetInitializers((Collection) getSpringFactoriesInstances(ApplicationContextInitializer.class));设置默认的initializerssetListeners((Collection) getSpringFactoriesInstances(ApplicationListener.class));设置默认的listenersthis.mainApplicationClass = deduceMainApplicationClass();