第一篇分析了springboot的启动流程和tomcat内嵌过程。文章地址:https://blog.csdn.net/qq_39404258/article/details/111191959。
该篇将重点分析一下事件驱动机制与配置文件加载。
事件驱动机制
事件驱动机制是指在持续事务管理过程中,进行决策的一种策略,即跟随当前时间点上出现的事件,调动可用资源,执行相关任务,使不断出现的问题得以解决,防止事务堆积。
事件驱动的一个常见形式便是发布-订阅模式。
事件机制主要由三个部分组成:事件源(source),事件对象(event),监听器(listener)
监听器只监听自己感兴趣的事件。
如何添加全局监听
有五种方法,其中4、5是springboot特有的。
1.addApplicationListener 方法
2.注册为bean
3.@EventListener
4.yml --context.listener.classes
5.spring.factories 自动配置
几种用法参考这个吧,写的很详细:https://www.cnblogs.com/linlf03/p/12332844.html。
这里面有两点是需要注意的:
1.事件驱动机制默认是同步方法,如何需要异步需要在监听器的方法上加@Async
2.比如使用第四种写法,但要监听配置文件加载之前的监听,这个时候监听器就不起作用,需要改为在监听触发之前就加载完毕的,如第五种方式。
事务驱动过程源码分析
回到springboot启动核心run方法
public ConfigurableApplicationContext run(String... args) {
StopWatch stopWatch = new StopWatch(); //记录运行时间
stopWatch.start();
ConfigurableApplicationContext context = null;
Collection<SpringBootExceptionReporter> exceptionReporters = new ArrayList<>();
//java.awt.headless是J2SE的一种模式用于在缺少显示屏、键盘或者鼠标时的系统配置,很多监控工具如jconsole
// 需要将该值设置为true,系统变量默认为true
configureHeadlessProperty();
//从META-INF/spring.factories中获取监听器 SpringApplicationRunListeners
SpringApplicationRunListeners listeners = getRunListeners(args);
listeners.starting();//遍历回调SpringApplicationRunListeners的starting方法
try {
//封装命令行参数
ApplicationArguments applicationArguments = new DefaultApplicationArguments(args);
//构造应用上下文环境,完成后回调SpringApplicationRunListeners的environmentPrepared方法
ConfigurableEnvironment environment = prepareEnvironment(listeners, applicationArguments);
configureIgnoreBeanInfo(environment);//处理需要忽略的Bean
Banner printedBanner = printBanner(environment);//打印banner
//根据是否web环境创建相应的IOC容器
context = createApplicationContext();
//实例化SpringBootExceptionReporter,用来支持报告关于启动的错误
exceptionReporters = getSpringFactoriesInstances(SpringBootExceptionReporter.class,
new Class[] { ConfigurableApplicationContext.class}, context);
//准备上下文环境,将environment保持到IOC容器中
//执行applyInitializers,遍历回调ApplicationContextInitializer的initialize方法
//遍历回调SpringApplicationRunListeners的contextPrepared方法
//遍历回调SpringApplicationRunListeners的contextLoaded方法
prepareContext(context, environment, listeners, applicationArguments, printedBanner);
refreshContext(context);//刷新应用上下文,组件扫描、创建、加载,同spring的refresh方法
//从IOC容器获取所有的ApplicationRunner(先调用)和CommandLinedRunner进行回调
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;
}
查看getRunListeners(args);方法
private SpringApplicationRunListeners getRunListeners(String[] args) {
Class<?>[] types = new Class<?>[] { SpringApplication.class, String[].class };
return new SpringApplicationRunListeners(logger,
getSpringFactoriesInstances(SpringApplicationRunListener.class, types, this, args));
}
这里从spring.factories中获取SpringApplicationRunListener.class实例,SpringApplicationRunListener.class对应的是EventPublishingRunListener这个实现类。
进入到EventPublishingRunListener类中查看
public EventPublishingRunListener(SpringApplication application, String[] args) {
this.application = application;
this.args = args;
//创建一个广播器,实例对象为SimpleApplicationEventMulticaster
this.initialMulticaster = new SimpleApplicationEventMulticaster();
for (ApplicationListener<?> listener : application.getListeners()) {
//将spring.factories中的监听器传递到SimpleApplicationEventMulticaster中。
this.initialMulticaster.addApplicationListener(listener);
}
}
回到run方法继续执行,执行listeners.starting();方法,进入starting()方法查看
public void starting() {
//创建application启动事件并发布
this.initialMulticaster.multicastEvent(new ApplicationStartingEvent(this.application, this.args));
}
--
public void multicastEvent(final ApplicationEvent event, @Nullable ResolvableType eventType) {
ResolvableType type = (eventType != null ? eventType : resolveDefaultEventType(event));
Executor executor = getTaskExecutor();
//找到匹配event的监听器
for (ApplicationListener<?> listener : getApplicationListeners(event, type)) {
if (executor != null) {
//异步监听
executor.execute(() -> invokeListener(listener, event));
}
else {
//同步监听
invokeListener(listener, event);
}
}
}
具体调用invokeListener()->doInvokeListener()->listener.onApplicationEvent(event);
监听器已经全部进入到ac容器内了,只有它感兴趣的事件到来时会触发这个监听的onApplicationEvent方法。
比如这样写context.publishEvent(new LogoutEvent("bbb"));就是发布一个事件
看一下publishEvent方法,最终还是调用了multicastEvent()方法
protected void publishEvent(Object event, @Nullable ResolvableType eventType) {
Assert.notNull(event, "Event must not be null");
// Decorate event as an ApplicationEvent if necessary
ApplicationEvent applicationEvent;
if (event instanceof ApplicationEvent) {
applicationEvent = (ApplicationEvent) event;
}
else {
applicationEvent = new PayloadApplicationEvent<>(this, event);
if (eventType == null) {
eventType = ((PayloadApplicationEvent<?>) applicationEvent).getResolvableType();
}
}
// Multicast right now if possible - or lazily once the multicaster is initialized
if (this.earlyApplicationEvents != null) {
this.earlyApplicationEvents.add(applicationEvent);
}
else {
//还是调用了这个方法
getApplicationEventMulticaster().multicastEvent(applicationEvent, eventType);
}
// Publish event via parent context as well...
if (this.parent != null) {
if (this.parent instanceof AbstractApplicationContext) {
((AbstractApplicationContext) this.parent).publishEvent(event, eventType);
}
else {
this.parent.publishEvent(event);
}
}
}
配置文件加载源码分析
回到run方法,看这一行代码,去准备容器环境
ConfigurableEnvironment environment = prepareEnvironment(listeners, applicationArguments);
这个方法里有一个这样的方法,去创建了一个ApplicationEnvironmentPreparedEvent事件
listeners.environmentPrepared(environment);
我们来到这个类中,ConfigFileApplicationListener,看里面这个监听方法,这些监听器在starting的时候就已经都记载到ac容器了,当这个ApplicationEnvironmentPreparedEvent事件发布时,这个onApplicationEvent会监听到这个ApplicationEnvironmentPreparedEvent事件,因为ApplicationEnvironmentPreparedEvent是ApplicationEvent 的子类
public void onApplicationEvent(ApplicationEvent event) {
if (event instanceof ApplicationEnvironmentPreparedEvent) {
onApplicationEnvironmentPreparedEvent((ApplicationEnvironmentPreparedEvent) event);
}
if (event instanceof ApplicationPreparedEvent) {
onApplicationPreparedEvent(event);
}
}
进入到onApplicationEnvironmentPreparedEvent()方法,它既是一个监听器,又是一个后置处理器
private void onApplicationEnvironmentPreparedEvent(ApplicationEnvironmentPreparedEvent event) {
List<EnvironmentPostProcessor> postProcessors = loadPostProcessors();
postProcessors.add(this);
AnnotationAwareOrderComparator.sort(postProcessors);
for (EnvironmentPostProcessor postProcessor : postProcessors) {
//调用后置处理方法
postProcessor.postProcessEnvironment(event.getEnvironment(), event.getSpringApplication());
}
}
选择ConfigFileApplicationListener类的postProcessEnvironment方法,到这个方法
protected void addPropertySources(ConfigurableEnvironment environment, ResourceLoader resourceLoader) {
RandomValuePropertySource.addToEnvironment(environment);
new Loader(environment, resourceLoader).load();
}
进入load()方法查看,先看到 initializeProfiles();方法,while循环稍后分析。
void load() {
FilteredPropertySource.apply(this.environment, DEFAULT_PROPERTIES, LOAD_FILTERED_PROPERTY,
(defaultProperties) -> {
//存储配置文件
this.profiles = new LinkedList<>();
//存储配置文件后缀
this.processedProfiles = new LinkedList<>();
//存储spring.profiles.active的状态
this.activatedProfiles = false;
//存储已加载的配置文件
this.loaded = new LinkedHashMap<>();
initializeProfiles();
while (!this.profiles.isEmpty()) {
Profile profile = this.profiles.poll();
if (isDefaultProfile(profile)) {
addProfileToEnvironment(profile.getName());
}
load(profile, this::getPositiveProfileFilter,
addToLoaded(MutablePropertySources::addLast, false));
this.processedProfiles.add(profile);
}
load(null, this::getNegativeProfileFilter, addToLoaded(MutablePropertySources::addFirst, true));
addLoadedPropertySources();
applyActiveProfiles(defaultProperties);
});
}
进入到 initializeProfiles();方法
private void initializeProfiles() {
// 先设置一个null对象,使它在list中是优先级最高的存在
this.profiles.add(null);
Binder binder = Binder.get(this.environment);
//spring.profiles.active 从environment属性中获取(正常情况是空,可以通过命令行设置),激活的文件
Set<Profile> activatedViaProperty = getProfiles(binder, ACTIVE_PROFILES_PROPERTY);
//spring.profiles.active 从environment属性中获取(正常情况是空,可以通过命令行设置),激活的文件
Set<Profile> includedViaProperty = getProfiles(binder, INCLUDE_PROFILES_PROPERTY);
//递归得到includedViaProperty里面的内容
List<Profile> otherActiveProfiles = getOtherActiveProfiles(activatedViaProperty, includedViaProperty);
//将获得的内容添加到存储配置文件字段
this.profiles.addAll(otherActiveProfiles);
// Any pre-existing active profiles set via property sources (e.g.
// System properties) take precedence over those added in config files.
this.profiles.addAll(includedViaProperty);
addActiveProfiles(activatedViaProperty);
//this.profiles只有一个null时(也就是没有通过参数配置)
if (this.profiles.size() == 1) { // only has null profile
for (String defaultProfileName : this.environment.getDefaultProfiles()) {
//获取到default的配置文件
Profile defaultProfile = new Profile(defaultProfileName, true);
//将这个默认的添加进来
this.profiles.add(defaultProfile);
}
}
}
回到load()方法,看这个while循环,这个代码就特别有意思了。这时this.profiles有两个参数,null和defaultProfile。我们先进入第一轮循环
while (!this.profiles.isEmpty()) {
//取出this.profiles第一个参数,也就是null
Profile profile = this.profiles.poll();
//里面执行了 不是null并且不是默认配置 ,不符合跳过
if (isDefaultProfile(profile)) {
addProfileToEnvironment(profile.getName());
}
load(profile, this::getPositiveProfileFilter,
addToLoaded(MutablePropertySources::addLast, false));
this.processedProfiles.add(profile);
}
进入load()方法
private void load(Profile profile, DocumentFilterFactory filterFactory, DocumentConsumer consumer) {
//将配置文件按照几个路径循环找出来
getSearchLocations().forEach((location) -> {
boolean isDirectory = location.endsWith("/");
Set<String> names = isDirectory ? getSearchNames() : NO_SEARCH_NAMES;
//将获取到的name进入这个load方法循环
names.forEach((name) -> load(location, name, profile, filterFactory, consumer));
});
}
继续进入load()方法
private void load(String location, String name, Profile profile, DocumentFilterFactory filterFactory,
DocumentConsumer consumer) {
if (!StringUtils.hasText(name)) {
for (PropertySourceLoader loader : this.propertySourceLoaders) {
if (canLoadFileExtension(loader, location)) {
load(loader, location, profile, filterFactory.getDocumentFilter(profile), consumer);
return;
}
}
throw new IllegalStateException("File extension of config file location '" + location
+ "' is not known to any PropertySourceLoader. If the location is meant to reference "
+ "a directory, it must end in '/'");
}
Set<String> processed = new HashSet<>();
//this.propertySourceLoaders是yml和properties配置文件类
for (PropertySourceLoader loader : this.propertySourceLoaders) {
//loader.getFileExtensions()指文件后缀,
//properties的后缀为.properties和.xml,
//yml的后缀为.yml和.yaml
for (String fileExtension : loader.getFileExtensions()) {
if (processed.add(fileExtension)) {
loadForFileExtension(loader, location + name, "." + fileExtension, profile, filterFactory,
consumer);
}
}
}
}
因为我写的配置是yml文件,所以直接看yml文件的执行流程。进入loadForFileExtension()方法
private void loadForFileExtension(PropertySourceLoader loader, String prefix, String fileExtension,
Profile profile, DocumentFilterFactory filterFactory, DocumentConsumer consumer) {
DocumentFilter defaultFilter = filterFactory.getDocumentFilter(null);
DocumentFilter profileFilter = filterFactory.getDocumentFilter(profile);
//因为现在profile==null所以不走这段逻辑
if (profile != null) {
// Try profile-specific file & profile section in profile file (gh-340)
String profileSpecificFile = prefix + "-" + profile + fileExtension;
load(loader, profileSpecificFile, profile, defaultFilter, consumer);
load(loader, profileSpecificFile, profile, profileFilter, consumer);
// Try profile specific sections in files we've already processed
for (Profile processedProfile : this.processedProfiles) {
if (processedProfile != null) {
String previouslyLoaded = prefix + "-" + processedProfile + fileExtension;
load(loader, previouslyLoaded, profile, profileFilter, consumer);
}
}
}
// Also try the profile-specific section (if any) of the normal file
load(loader, prefix + fileExtension, profile, profileFilter, consumer);
}
继续向load()方法里面走,因为我的yml配置文件写在resource文件夹下,所以当目录循环到classpath:/application.yml
private void load(PropertySourceLoader loader, String location, Profile profile, DocumentFilter filter,
DocumentConsumer consumer) {
//当location是位于我写的文件夹下,可以获取到资源
Resource[] resources = getResources(location);
for (Resource resource : resources) {
try {
if (resource == null || !resource.exists()) {
if (this.logger.isTraceEnabled()) {
StringBuilder description = getDescription("Skipped missing config ", location, resource,
profile);
this.logger.trace(description);
}
continue;
}
if (!StringUtils.hasText(StringUtils.getFilenameExtension(resource.getFilename()))) {
if (this.logger.isTraceEnabled()) {
StringBuilder description = getDescription("Skipped empty config extension ", location,
resource, profile);
this.logger.trace(description);
}
continue;
}
String name = "applicationConfig: [" + getLocationName(location, resource) + "]";
//加载文件资源
List<Document> documents = loadDocuments(loader, name, resource);
if (CollectionUtils.isEmpty(documents)) {
if (this.logger.isTraceEnabled()) {
StringBuilder description = getDescription("Skipped unloaded config ", location, resource,
profile);
this.logger.trace(description);
}
continue;
}
List<Document> loaded = new ArrayList<>();
for (Document document : documents) {
//对文件资源进行匹配
if (filter.match(document)) {
//将对应的资源存储到对应的位置,这里面的逻辑为:
//1.将默认的将解析到的spring.profiles.active的值放入到this.profiles
//2.将this.activatedProfiles 改为 true
//3.将default的内容移除,
//这时this.profiles就变为了 active了,这也是最开始给this.profiles添加一个null的作用,null已经被取走了,default被替换掉了
addActiveProfiles(document.getActiveProfiles());
addIncludedProfiles(document.getIncludeProfiles());
//将这个资源存储到已经加载过的资源里面,防止二次加载
loaded.add(document);
}
}
Collections.reverse(loaded);
if (!loaded.isEmpty()) {
loaded.forEach((document) -> consumer.accept(profile, document));
if (this.logger.isDebugEnabled()) {
StringBuilder description = getDescription("Loaded config file ", location, resource,
profile);
this.logger.debug(description);
}
}
}
catch (Exception ex) {
StringBuilder description = getDescription("Failed to load property source from ", location,
resource, profile);
throw new IllegalStateException(description.toString(), ex);
}
}
}
进入到loadDocuments()方法中查看
private List<Document> loadDocuments(PropertySourceLoader loader, String name, Resource resource)
throws IOException {
DocumentsCacheKey cacheKey = new DocumentsCacheKey(loader, resource);
List<Document> documents = this.loadDocumentsCache.get(cacheKey);
if (documents == null) {
//找对应的类解析
List<PropertySource<?>> loaded = loader.load(name, resource);
//封装解析内容
documents = asDocuments(loaded);
this.loadDocumentsCache.put(cacheKey, documents);
}
return documents;
}
进入到asDocuments()方法查看
private List<Document> asDocuments(List<PropertySource<?>> loaded) {
if (loaded == null) {
return Collections.emptyList();
}
return loaded.stream().map((propertySource) -> {
Binder binder = new Binder(ConfigurationPropertySources.from(propertySource),
this.placeholdersResolver);
String[] profiles = binder.bind("spring.profiles", STRING_ARRAY).orElse(null);
//将spring.profiles.active的值存起来
Set<Profile> activeProfiles = getProfiles(binder, ACTIVE_PROFILES_PROPERTY);
//将spring.profiles.include的值存起来
Set<Profile> includeProfiles = getProfiles(binder, INCLUDE_PROFILES_PROPERTY);
return new Document(propertySource, profiles, activeProfiles, includeProfiles);
}).collect(Collectors.toList());
}
到这里第一轮为null的循环就结束了,回到while循环。这时的this.profiles就剩active配置文件了,解释在 addActiveProfiles()上面。这也是最开始给this.profiles添加一个null的作用,null已经被取走了,default被替换掉了
while (!this.profiles.isEmpty()) {
//第二轮循环,profile的name已经变为active了
Profile profile = this.profiles.poll();
if (isDefaultProfile(profile)) {
addProfileToEnvironment(profile.getName());
}
load(profile, this::getPositiveProfileFilter,
addToLoaded(MutablePropertySources::addLast, false));
this.processedProfiles.add(profile);
}
然后走同样的逻辑直到asDocuments()方法,在这里查看一下documents的内容,已经将yml文件配置信息全部获取了。
总结一下:事务驱动机制就是监听器模式让springboot封装了一层。而配置文件加载也是基于事务驱动机制的。