SpringApplication

点开SpringApplication源码会发现开头注解已经介绍了这个类的作用,就是加载spring应用bootstrap。

具体步骤

  1. 根据你的classpath创建一个适当的spring实例(web,none)

  2. 注册一个commandlinepropertysource,暴露一个命令行给spring配置

  3. 刷新context上下文

  4. 触发后置的一些bean,如commandlinerunner

构造器分析

构造期参数有两个,一个为resourceloader,一个为class数组

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 = WebApplicationType.deduceFromClasspath();//判断web容器类型
   setInitializers((Collection) getSpringFactoriesInstances(ApplicationContextInitializer.class));//设置pre context 的初始化工具类
   setListeners((Collection) getSpringFactoriesInstances(ApplicationListener.class));//设置监听器   
   this.mainApplicationClass = deduceMainApplicationClass();//寻找main的类
}
	private <T> Collection<T> getSpringFactoriesInstances(Class<T> type, Class<?>[] parameterTypes, Object... args) {
		ClassLoader classLoader = getClassLoader();
		// Use names and ensure unique to protect against duplicates
		Set<String> names = new LinkedHashSet<>(SpringFactoriesLoader.loadFactoryNames(type, classLoader));
		List<T> instances = createSpringFactoriesInstances(type, parameterTypes, classLoader, args, names);
		AnnotationAwareOrderComparator.sort(instances);
		return instances;
	}
  • WebApplicationType 一般为servlet,内部实现通过catch class.forName 是否能找到对应type类

  • 先看getSpringFacotryiesInstances方法,看名字大概也能猜到就是利用spi机制创建springboot的基础配置,位置就在META-INF/spring.factories

  • mainApplicationClass利用创建new RuntimeException 获取StackTrace 然后迭代栈判断方法名是否为main

Run

  1. 计时器启动

  2. configureHeadlessProperty不用关心

  3. 获取SpringApplicationRunListeners,内部实现和上面实例application差不多

  4. prepareEnviroment

  5. 下面不写了 累了 下次补充

Last updated

Was this helpful?