内容纲要
1.构建 SpringApplication(加载所需的基本配置和引入jar包所包含的需要注册bean配置)
public SpringApplication(ResourceLoader resourceLoader, Class>... primarySources) {
//默认为空,后面会取默认实现(classLoader和resourceLoader有关联)
this.resourceLoader = resourceLoader;
Assert.notNull(primarySources, "PrimarySources must not be null");
//排除重复类
this.primarySources = new LinkedHashSet<>(Arrays.asList(primarySources));
//判断应用类型,常用web应用为servlet
this.webApplicationType = WebApplicationType.deduceFromClasspath();
//从所有jar包的"META-INF/spring.factories"文件查找一下三种配置
//jar包中的配置是在这一步加载的与项目内自身代码中配置加载是有区别的
//获取Bootstrapper(不推荐)和BootstrapRegistryInitializer配置
this.bootstrapRegistryInitializers = getBootstrapRegistryInitializersFromSpringFactories();
//获取ApplicationContextInitializer配置
setInitializers((Collection) getSpringFactoriesInstances(ApplicationContextInitializer.class));
//获取ApplicationListener配置
setListeners((Collection) getSpringFactoriesInstances(ApplicationListener.class));
this.mainApplicationClass = deduceMainApplicationClass();
}
2.运行SpringApplication
public ConfigurableApplicationContext run(String... args) {
StopWatch stopWatch = new StopWatch();
stopWatch.start();
DefaultBootstrapContext bootstrapContext = createBootstrapContext();
ConfigurableApplicationContext context = null;
//告诉服务器使用的是服务运行环境(无显示器、键盘输入)
configureHeadlessProperty();
//从spring.factories加载SpringApplicationRunListener配置
SpringApplicationRunListeners listeners = getRunListeners(args);
listeners.starting(bootstrapContext, this.mainApplicationClass);
try {
ApplicationArguments applicationArguments = new DefaultApplicationArguments(args);
ConfigurableEnvironment environment = prepareEnvironment(listeners, bootstrapContext, applicationArguments);
configureIgnoreBeanInfo(environment);
Banner printedBanner = printBanner(environment);
context = createApplicationContext();
context.setApplicationStartup(this.applicationStartup);
prepareContext(bootstrapContext, context, environment, listeners, applicationArguments, printedBanner);
//加载项目下的bean
refreshContext(context);
afterRefresh(context, applicationArguments);
if (this.logStartupInfo) {
new StartupInfoLogger(this.mainApplicationClass).logStarted(getApplicationLog(), stopWatch);
}
listeners.started(context);
callRunners(context, applicationArguments);
}
catch (Throwable ex) {
handleRunFailure(context, ex, listeners);
throw new IllegalStateException(ex);
}
try {
listeners.running(context);
}
catch (Throwable ex) {
handleRunFailure(context, ex, null);
throw new IllegalStateException(ex);
}
return context;
}
3.@EnableAutoConfiguration
注解会加载pom jar目录META-INF/spring.factories里定义的 EnableAutoConfiguration配置
这一过程中springboot都是从pom引入的jar包目录META-INF/spring.factories文件里加载的配置,是将引入的jar里需要注册的bean注册到spring-boot项目的spring容器中。由于@ComponentScan注解只能扫描spring-boot项目包内的bean并注册到spring容器中,因此需要@EnableAutoConfiguration注解来注册项目包外的bean。而spring.factories文件,则是用来记录项目包外需要注册的bean类名。
也就是说如果我们的jar需要被引入是注册bean的话,也需要提供spring.factories文件