Springboot的启动和Spring中的事件编程模型紧密相关。因为在springboot启动过程中,监听器起到了很关键的作用。
入口方法:
-
调用静态run方法,本质上还是实例化然后run
SpringApplication.run(BootDemo1Application.class , args);
-
实例化SpringApplication对象,然后调用run方法
new SpringApplication(BootDemo1Application.class).run(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
// SpringFactoriesLoader.loadFactoryNames(type, classLoader) 使用class的全名去spring.factories文找到所有的值
// 这里使用Set可以起到去重的作用
Set<String> names = new LinkedHashSet<>(SpringFactoriesLoader.loadFactoryNames(type, classLoader));
// 将set集合中className对应的对象创建出来
List<T> instances = createSpringFactoriesInstances(type, parameterTypes, classLoader, args, names);
// 对所有创建出来的对象进行排序
// Order Priority => value进行排序
AnnotationAwareOrderComparator.sort(instances);
return instances;
}
public static List<String> loadFactoryNames(Class<?> factoryClass, @Nullable ClassLoader classLoader) {
// 获取key
String factoryClassName = factoryClass.getName();
// 根据key去资源文件下寻找 就是读取properties文件的操作
return loadSpringFactories(classLoader).getOrDefault(factoryClassName, Collections.emptyList());
}
private static Map<String, List<String>> loadSpringFactories(@Nullable ClassLoader classLoader) {
MultiValueMap<String, String> result = cache.get(classLoader);
// 存在缓存的情况下,说明所有文件已经load完成了
if (result != null) {
return result;
}
try {
Enumeration<URL> urls = (classLoader != null ?
classLoader.getResources(FACTORIES_RESOURCE_LOCATION) :
ClassLoader.getSystemResources(FACTORIES_RESOURCE_LOCATION));
result = new LinkedMultiValueMap<>();
// 一次遍历了依赖中所有 spring.factories 文件
while (urls.hasMoreElements()) {
URL url = urls.nextElement();
UrlResource resource = new UrlResource(url);
// 读取properties文件
Properties properties = PropertiesLoaderUtils.loadProperties(resource);
// 使用 entry 遍历
for (Map.Entry<?, ?> entry : properties.entrySet()) {
// 去前后空格并进行分割
String factoryClassName = ((String) entry.getKey()).trim();
for (String factoryName : StringUtils.commaDelimitedListToStringArray((String) entry.getValue())) {
result.add(factoryClassName, factoryName.trim());
}
}
}
// 放入缓存中
cache.put(classLoader, result);
return result;
} catch (IOException ex) {
throw new IllegalArgumentException("Unable to load factories from location [" +
FACTORIES_RESOURCE_LOCATION + "]", ex);
}
}
运行流程:org.springframework.boot.SpringApplication
1、构建SpringApplication对象
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();
// 初始化容器初始化器
// getSpringFactoriesInstances(ApplicationContextInitializer.class) 这个方法非常关键
// 就是从当前classpath:META-INF/spring.factories 中获取所有的key=传入class全名的所有值
// 并且将这些值对应的对象实例化出来,然后放入集合中,返回这样一个集合对象
// key=org.springframework.context.ApplicationContextInitializer
// org.springframework.boot.context.ConfigurationWarningsApplicationContextInitializer
// org.springframework.boot.context.ContextIdApplicationContextInitializer
// org.springframework.boot.context.config.DelegatingApplicationContextInitializer
// org.springframework.boot.web.context.ServerPortInfoApplicationContextInitializer
// org.springframework.boot.autoconfigure.SharedMetadataReaderFactoryContextInitializer
// org.springframework.boot.autoconfigure.logging.ConditionEvaluationReportLoggingListener
setInitializers((Collection) getSpringFactoriesInstances(ApplicationContextInitializer.class));
// 初始化所有的监听器 listener
// key = org.springframework.context.ApplicationListener
// org.springframework.boot.ClearCachesApplicationListener
// org.springframework.boot.builder.ParentContextCloserApplicationListener
// org.springframework.boot.context.FileEncodingApplicationListener
// org.springframework.boot.context.config.AnsiOutputApplicationListener
// org.springframework.boot.context.config.ConfigFileApplicationListener
// org.springframework.boot.context.config.DelegatingApplicationListener
// org.springframework.boot.context.logging.ClasspathLoggingApplicationListener
// org.springframework.boot.context.logging.LoggingApplicationListener
// org.springframework.boot.liquibase.LiquibaseServiceLocatorApplicationListener
// org.springframework.boot.autoconfigure.BackgroundPreinitializer
setListeners((Collection) getSpringFactoriesInstances(ApplicationListener.class));
// 推断main方法所在的类,应为有可能main方法所在的类和springBoot中的主配置类不是同一个类
// 所以这里需要解析这个主类 使用java中的异常栈技术,从异常栈信息中找出
// public static void main(String[] args) 这个方法所对应的类
// 具体内部是直接通过判断方法名称来确定main方法的
// mainApplicationClass = 主类的class对象
this.mainApplicationClass = deduceMainApplicationClass();
}
2、运行run方法
public ConfigurableApplicationContext run(String... args) {
// 计时组件
StopWatch stopWatch = new StopWatch();
stopWatch.start();
ConfigurableApplicationContext context = null;
Collection<SpringBootExceptionReporter> exceptionReporters = new ArrayList<>();
configureHeadlessProperty();
// 获取 spring.factories 中的key=org.springframework.boot.SpringApplicationRunListener 的监听器集合
SpringApplicationRunListeners listeners = getRunListeners(args);
// org.springframework.boot.context.event.EventPublishingRunListener
// 在创建这个 EventPublishingRunListener 对象的时候,会将容器中的所有listener添加到这个广播器中 initialMulticaster
// org.springframework.boot.context.event.EventPublishingRunListener.EventPublishingRunListener
// 发布starting事件 使用 EventPublishingRunListener 对象中的广播器 initialMulticaster
// 这个广播器会去广播对应的事件 initialMulticaster.multicastEvent(SpringApplicationEvent e)
// starting => ApplicationStartingEvent => supportsEvent(listener, eventType, sourceType) 获取感兴趣的监听器
// invokeListener(listener, event) => listener.onApplicationEvent(event);
// 第一个事件
listeners.starting();
try {
// 包装原始参数
ApplicationArguments applicationArguments = new DefaultApplicationArguments(args);
// 1、profile 2、加载外部的配置文件到environment 3、发布环境准备完成事件
// 4、绑定环境、
ConfigurableEnvironment environment = prepareEnvironment(listeners, applicationArguments);
//
configureIgnoreBeanInfo(environment);
// 是否打印banner
Banner printedBanner = printBanner(environment);
// 创建ApplicationContext
context = createApplicationContext();
// 获取spring.factories 文件中key=org.springframework.boot.SpringBootExceptionReporter
// org.springframework.boot.diagnostics.FailureAnalyzers
exceptionReporters = getSpringFactoriesInstances(SpringBootExceptionReporter.class,
new Class[] { ConfigurableApplicationContext.class }, context);
// 准备context 容器
prepareContext(context, environment, listeners, applicationArguments, printedBanner);
// 刷新容器 => context的父类 AbstractApplicationContext#refresh
refreshContext(context);
// 空方法
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;
}
2.1获取SpringApplicationRunListener
private SpringApplicationRunListeners getRunListeners(String[] args) {
Class<?>[] types = new Class<?>[] { SpringApplication.class, String[].class };
// getSpringFactoriesInstances(SpringApplicationRunListener.class, types, this, args)
// 拿所有的 SpringApplicationRunListener 类型的对象
return new SpringApplicationRunListeners(logger,
getSpringFactoriesInstances(SpringApplicationRunListener.class, types, this, args));
}
private <T> Collection<T> getSpringFactoriesInstances(Class<T> type) {
// 返回所有的实例对象集合
return getSpringFactoriesInstances(type, new Class<?>[] {});
}
2.2绑定环境
private ConfigurableEnvironment prepareEnvironment(SpringApplicationRunListeners listeners,ApplicationArguments applicationArguments) {
// Create and configure the environment
// 根据前面得到的applicationType来创建环境
// StandardServletEnvironment 标准的web环境 ...
ConfigurableEnvironment environment = getOrCreateEnvironment();
// 加载外部配置、解析命令行参数 和 Profile
configureEnvironment(environment, applicationArguments.getSourceArgs());
// 将configurationProperties和propertySource正确的关联起来
ConfigurationPropertySources.attach(environment);
// 第二个事件
// 发布环境准备完成事件
listeners.environmentPrepared(environment);
// 将环境绑定到Application中
bindToSpringApplication(environment);
if (!this.isCustomEnvironment) {
environment = new EnvironmentConverter(getClassLoader()).convertEnvironmentIfNecessary(environment,
deduceEnvironmentClass());
}
ConfigurationPropertySources.attach(environment);
return environment;
}
2.3创建ApplicationContext
protected ConfigurableApplicationContext createApplicationContext() {
Class<?> contextClass = this.applicationContextClass;
if (contextClass == null) {
try {
switch (this.webApplicationType) {
case SERVLET:
// AnnotationConfigServletWebServerApplicationContext
contextClass = Class.forName(DEFAULT_SERVLET_WEB_CONTEXT_CLASS);
break;
case REACTIVE:
// AnnotationConfigReactiveWebServerApplicationContext
contextClass = Class.forName(DEFAULT_REACTIVE_WEB_CONTEXT_CLASS);
break;
default:
// AnnotationConfigApplicationContext
contextClass = Class.forName(DEFAULT_CONTEXT_CLASS);
}
}catch (ClassNotFoundException ex) {
throw new IllegalStateException(
"Unable create a default ApplicationContext, " + "please specify an ApplicationContextClass",
ex);
}
}
return (ConfigurableApplicationContext) BeanUtils.instantiateClass(contextClass);
}
2.4准备刷新容器
private void prepareContext(ConfigurableApplicationContext context, ConfigurableEnvironment environment,
SpringApplicationRunListeners listeners, ApplicationArguments applicationArguments, Banner printedBanner) {
// 设置环境
context.setEnvironment(environment);
// 为spring注册一个beanName的生成器 ConfigurationBeanNameGenerator
postProcessApplicationContext(context);
// 调用所有 initializer 的 initializer.initialize(context); 方法
applyInitializers(context);
// 第三个事件 发布容器准备完成事件
listeners.contextPrepared(context);
if (this.logStartupInfo) {
logStartupInfo(context.getParent() == null);
logStartupProfileInfo(context);
}
// Add boot specific singleton beans
ConfigurableListableBeanFactory beanFactory = context.getBeanFactory();
// 向容器中注入bean
beanFactory.registerSingleton("springApplicationArguments", applicationArguments);
if (printedBanner != null) {
beanFactory.registerSingleton("springBootBanner", printedBanner);
}
if (beanFactory instanceof DefaultListableBeanFactory) {
((DefaultListableBeanFactory) beanFactory)
.setAllowBeanDefinitionOverriding(this.allowBeanDefinitionOverriding);
}
// Load the sources
Set<Object> sources = getAllSources();
Assert.notEmpty(sources, "Sources must not be empty");
// 这里并没有扫描包,只是将主程序中run方法中的参数进行解析,如果传入的类,会创建一个bd注册到容器中
// 如果传入一个包名,就会扫描对应的包,形成bd
// 这里并没有对整个应用程序进行包扫描
load(context, sources.toArray(new Object[0]));
// 第4个事件:发布容器加载完成事件
listeners.contextLoaded(context);
}