Springboot源码系列
一、SpringApplication的构造方法
springboot程序的一切都开始于main方法
public static void main(String[] args) {
SpringApplication.run(ZiyanApiApplication.class, args);
}
run方法中传入了两个参数一个是当前main方法的Class对象,一个是命令行的参数的数组,让我们来看看run方法中都做了哪些事情
/**
* Static helper that can be used to run a {@link SpringApplication} from the
* specified source using default settings.
* @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);
}
run方法为SpringApplication类的静态方法,在执行结束后会返回一个ConfigurableApplicationContext,在main方法中我们可以用一个变量接收这个返回的对象,供以后使用(是不是就不需要什么ApplicationContextAware了←_←),继续进入run方法的重载方法
public static ConfigurableApplicationContext run(Class<?>[] primarySources, String[] args) {
return new SpringApplication(primarySources).run(args);
}
先忽略run方法,在重载方法中新建了一个SpringApplication类对象,进入构造方法
public SpringApplication(Class<?>... primarySources) {
this(null, primarySources);
}
调用了构造方法的重载方法,进入重载的方法
public SpringApplication(ResourceLoader resourceLoader, Class<?>... primarySources) {
//由于还未加载任何resource,所以调用是传入的是null
this.resourceLoader = resourceLoader;
//检验main方法的Class类对象是否为null
Assert.notNull(primarySources, "PrimarySources must not be null");
//将main方法的Class对象保存起来
this.primarySources = new LinkedHashSet<>(Arrays.asList(primarySources));
//从类路径的Class判断应用的类型
//如果类路径中
//包含org.springframework.web.reactive.DispatcherHandler并且不包含org.springframework.web.servlet.DispatcherServlet并且不包含
//org.glassfish.jersey.servlet.ServletContainer则类型为REACTIVE
//如果类路径中
//不包含javax.servlet.Servlet或不包含org.springframework.web.context.ConfigurableWebApplicationContext则类型为NONE(普通的spring应
//用)
//如果不满足以上两种则为SERVLET(web应用且使用内置的server启动)
this.webApplicationType = WebApplicationType.deduceFromClasspath();//对于我的项目则为servlet
//注册BootstrapRegistryInitializers这个方法即将过时,在2.6.0中将会被移除
this.bootstrapRegistryInitializers = getBootstrapRegistryInitializersFromSpringFactories();
//注册一些Initializers实例
setInitializers((Collection) getSpringFactoriesInstances(ApplicationContextInitializer.