DemoApplication.java代码如下
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
现在来分析一下SpringApplication.run执行的流程:
- 1.创建了一个SpringApplication实例,并作为参数传递了主配置类
- 2.调用了SpringApplication.run(args)方法
- 创建实例
public SpringApplication(ResourceLoader resourceLoader, Class<?>... primarySources) {
// 设置resourceLoader
this.resourceLoader = resourceLoader;
// 断言资源类不能为null
Assert.notNull(primarySources, "PrimarySources must not be null");
// 赋值
this.primarySources = new LinkedHashSet<>(Arrays.asList(primarySources));
// >>> 1.推断当前应用的类型(根据当前classpath下是否包含某些类来确定)
this.webApplicationType = WebApplicationType.deduceFromClasspath();
// >>> 2.设置初始化器(从spring.factories获取ApplicationContextInitializer获取配置的类)
setInitializers((Collection) getSpringFactoriesInstances(ApplicationContextInitializer.class));
// >>> 3.设置监听器(从spring.factories中获取ApplicationListener配置的类)
setListeners((Collection) getSpringFactoriesInstances(ApplicationListener.class));
// >>> 4.推断MainApplicationClass(当前main方法所在的Class)
this.mainApplicationClass = deduceMainApplicationClass();
}
- run方法
/**
* Run the Spring application, creating and refreshing a new
* {@link ApplicationContext}.
* @param args the application arguments (usually passed from a Java main method)
* @return a running {@link ApplicationContext}
*/
public ConfigurableApplicationContext run(String... args) {
// 应用启动时间记录器
StopWatch stopWatch = new StopWatch();
stopWatch.start();
ConfigurableApplicationContext context = null;
Collection<SpringBootExceptionReporter> exceptionReporters = new ArrayList<>();
configureHeadlessProperty();
// 1.获取监听器并触发事件(从spring.factories中获取SpringApplicationRunListener配置的类,并初始化作为监听器)
// SpringApplicationRunListener负责在SpringBootApplication的不同生命周期广播出不同的事件,传递给ApplicationListener
SpringApplicationRunListeners listeners = getRunListeners(args);
// 触发
listeners.starting();
try {
// 2.初始化环境
ApplicationArguments applicationArguments = new DefaultApplicationArguments(args);
ConfigurableEnvironment environment = prepareEnvironment(listeners, applicationArguments);
configureIgnoreBeanInfo(environment);
Banner printedBanner = printBanner(environment);
// 3.创建应用上下文对象,初始化IOC容器(ioc容器创建后作为一个属性存在context中)
context = createApplicationContext();
// 取到关于SpringBoot异常报告的一些报告器
exceptionReporters = getSpringFactoriesInstances(SpringBootExceptionReporter.class,
new Class[] { ConfigurableApplicationContext.class }, context);
// 4.刷新IOC容器前的处理
prepareContext(context, environment, listeners, applicationArguments, printedBanner);
// 5.刷新IOC容器,
// 调用IOC容器的refresh,触发invokeBeanFactoryPostProcessors(),此步骤中
// 会调用ConfigurationClassParser.parse去解析主配置类(启动类),识别ComponentScan等注解来解析配置类
refreshContext(context);
// 6.刷新IOC容器后的处理
afterRefresh(context, applicationArguments);
stopWatch.stop();
if (this.logStartupInfo) {
new StartupInfoLogger(this.mainApplicationClass).logStarted(getApplicationLog(), stopWatch);
}
listeners.started(context);
callRunners(context, applicationArguments);
}
catch (Throwable ex) {
handleRunFailure(context, ex, exceptionReporters, listeners);
throw new IllegalStateException(ex);
}
try {
listeners.running(context);
}
catch (Throwable ex) {
handleRunFailure(context, ex, exceptionReporters, null);
throw new IllegalStateException(ex);
}
return context;
}
核心步骤:
- 1、获取RunListener并启动这些监听器
// 1.获取监听器并触发事件(从spring.factories中获取SpringApplicationRunListener配置的类,并初始化作为监听器)
// SpringApplicationRunListener负责在SpringBootApplication的不同生命周期广播出不同的事件,传递给ApplicationListener
SpringApplicationRunListeners listeners = getRunListeners(args);
listeners.starting();
什么是RunListener呢,我们看下getRunListeners方法:
private SpringApplicationRunListeners getRunListeners(String[] args) {
Class<?>[] types = new Class<?>[] { SpringApplication.class, String[].class };
return new SpringApplicationRunListeners(logger,
getSpringFactoriesInstances(SpringApplicationRunListener.class, types, this, args));
}
核心代码是getSpringFactoriesInstances(SpringApplicationRunListener.class, types, this, args);
继续看这个方法源码
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;
}
其核心代码是SpringFactoriesLoader.loadFactoryNames(type, classLoader);
再看这个loadFactoryNames方法:
注释已经说明了本方法的作用,通过给定的类加载器从FACTORY_RESOURCE_LOCATION这个位置去加载指定的工厂类型。
如图中箭头指向所示:
- 1、先调用了重载方法loadSpringFactories(ClassLoader classloader)
- 2、重载方法中从指定路径(META-INF/spring.factories)中加载所有类全限定名
- 3、通过传入的工厂类型名称,取出本次需要(指定类型)的工厂类型名称集合
那么,这里就是加载所有的SpringApplicationRunListener所配置的类集合,我们从META-INF/spring.factories中找到这个SpringApplicationRunListener
可以看到搜索文件时,会显示很多个spring.factories,很多jar中都有这个路径的资源文件。实质上,springboot会加载每个jar中的spring.factories中的内容,这也就是starter扩展机制,我们自定义starter时,只需要在自己的jar中的META-INF/spring.factories中配置上自己的。
可以看到这个spring.factories中有很多个KEY=VALUE的配置,其格式与properties并无二致,每个KEY都是一个接口,VALUE对应一个字符串, VALUE中多个类全限定名用逗号分割,每个全限定名对应的类都是KEY这个接口的实现类(直接或间接实现)。
SpringApplicationRunListener:
其注释已经说得比较清楚了:监听SpringApplication的run方法。
至此,SpringApplication.run(ClassLoader classLoader)中的第一步,获取监听器并执行分析结束。
- 2、初始化环境
// 2.初始化环境
ApplicationArguments applicationArguments = new DefaultApplicationArguments(args);
ConfigurableEnvironment environment = prepareEnvironment(listeners, applicationArguments);
configureIgnoreBeanInfo(environment);
Banner printedBanner = printBanner(environment);
这一步主要是环境准备工作:
- 2.1 参数提取,将args中的参数重新包装为ApplicationArguments
- 2.2 准备环境
private ConfigurableEnvironment prepareEnvironment(SpringApplicationRunListeners listeners,
ApplicationArguments applicationArguments) {
// Create and configure the environment
// 根据应用类型创建相应的环境对象
ConfigurableEnvironment environment = getOrCreateEnvironment();
// 配置一些属性,包括解析args参数,设置activeProfiles等
configureEnvironment(environment, applicationArguments.getSourceArgs());
ConfigurationPropertySources.attach(environment);
// 触发监听器,包括ConfigFileApplicationListener会在这一步根据配置文件位置找到对应的配置文件并加载到environment中
listeners.environmentPrepared(environment);
bindToSpringApplication(environment);
if (!this.isCustomEnvironment) {
environment = new EnvironmentConverter(getClassLoader()).convertEnvironmentIfNecessary(environment,
deduceEnvironmentClass());
}
ConfigurationPropertySources.attach(environment);
return environment;
}
- 2.3 配置忽略的bean信息
private void configureIgnoreBeanInfo(ConfigurableEnvironment environment) {
if (System.getProperty(CachedIntrospectionResults.IGNORE_BEANINFO_PROPERTY_NAME) == null) {
Boolean ignore = environment.getProperty("spring.beaninfo.ignore", Boolean.class, Boolean.TRUE);
System.setProperty(CachedIntrospectionResults.IGNORE_BEANINFO_PROPERTY_NAME, ignore.toString());
}
}
- 2.4 打印Banner
private Banner printBanner(ConfigurableEnvironment environment) {
if (this.bannerMode == Banner.Mode.OFF) {
return null;
}
ResourceLoader resourceLoader = (this.resourceLoader != null) ? this.resourceLoader
: new DefaultResourceLoader(getClassLoader());
SpringApplicationBannerPrinter bannerPrinter = new SpringApplicationBannerPrinter(resourceLoader, this.banner);
if (this.bannerMode == Mode.LOG) {
return bannerPrinter.print(environment, this.mainApplicationClass, logger);
}
return bannerPrinter.print(environment, this.mainApplicationClass, System.out);
}
SpringBoot项目中,默认会打印springboot的banner,当然我们可以通过"spring.banner.image.location"或者"spring.banner.location"来配置我们自己的项目banner
3.创建applicationContext
/**
* Strategy method used to create the {@link ApplicationContext}. By default this
* method will respect any explicitly set application context or application context
* class before falling back to a suitable default.
* @return the application context (not yet refreshed)
* @see #setApplicationContextClass(Class)
*/
protected ConfigurableApplicationContext createApplicationContext() {
// 获取class
Class<?> contextClass = this.applicationContextClass;
if (contextClass == null) {
try {
switch (this.webApplicationType) {
case SERVLET:
contextClass = Class.forName(DEFAULT_SERVLET_WEB_CONTEXT_CLASS);
break;
case REACTIVE:
contextClass = Class.forName(DEFAULT_REACTIVE_WEB_CONTEXT_CLASS);
break;
default:
contextClass = Class.forName(DEFAULT_CONTEXT_CLASS);
}
}
catch (ClassNotFoundException ex) {
throw new IllegalStateException(
"Unable create a default ApplicationContext, please specify an ApplicationContextClass", ex);
}
}
// 创建ApplicationContext实例
return (ConfigurableApplicationContext) BeanUtils.instantiateClass(contextClass);
}
根据应用类型,实例化相应的applicationContext。
4 刷新IOC容器前的处理
/**
* 完成相关属性的设置
* 完成一些bean的创建
* @param context
* @param environment
* @param listeners
* @param applicationArguments
* @param printedBanner
*/
private void prepareContext(ConfigurableApplicationContext context, ConfigurableEnvironment environment,
SpringApplicationRunListeners listeners, ApplicationArguments applicationArguments, Banner printedBanner) {
// 设置环境到上下文中
context.setEnvironment(environment);
// 设置一些属性
postProcessApplicationContext(context);
// 遍历初始化器并执行
applyInitializers(context);
// 执行一些监听器
listeners.contextPrepared(context);
if (this.logStartupInfo) {
logStartupInfo(context.getParent() == null);
logStartupProfileInfo(context);
}
// Add boot specific singleton beans
ConfigurableListableBeanFactory beanFactory = context.getBeanFactory();
beanFactory.registerSingleton("springApplicationArguments", applicationArguments);
if (printedBanner != null) {
beanFactory.registerSingleton("springBootBanner", printedBanner);
}
if (beanFactory instanceof DefaultListableBeanFactory) {
((DefaultListableBeanFactory) beanFactory)
.setAllowBeanDefinitionOverriding(this.allowBeanDefinitionOverriding);
}
if (this.lazyInitialization) {
context.addBeanFactoryPostProcessor(new LazyInitializationBeanFactoryPostProcessor());
}
// Load the sources
Set<Object> sources = getAllSources();
Assert.notEmpty(sources, "Sources must not be empty");
// 将主启动类定义加载到IOC容器beanDefinitionMap中
load(context, sources.toArray(new Object[0]));
// 发布一些事件
listeners.contextLoaded(context);
}
5. 刷新IOC容器
private void refreshContext(ConfigurableApplicationContext context) {
if (this.registerShutdownHook) {
try {
context.registerShutdownHook();
}
catch (AccessControlException ex) {
// Not allowed in some environments.
}
}
refresh(context);
}
/**
* Refresh the underlying {@link ApplicationContext}.
* @param applicationContext the application context to refresh
*/
protected void refresh(ApplicationContext applicationContext) {
Assert.isInstanceOf(AbstractApplicationContext.class, applicationContext);
((AbstractApplicationContext) applicationContext).refresh();
}
最终调用applicationContext.refresh(),这里就回到了spring中ioc容器的refresh方法。
applicationContext.refresh中,会执行invokeBeanFactoryPostProcessors(),
此步骤中会调用ConfigurationClassParser.parse去解析主配置类(启动类),识别ComponentScan等注解并完成配置。
6.刷新IOC容器后的处理
/**
* Called after the context has been refreshed.
* @param context the application context
* @param args the application arguments
*/
protected void afterRefresh(ConfigurableApplicationContext context, ApplicationArguments args) {
}