springboot默认支持加载application.properties或者application.yml配置文件,我们有些散落的配置可以统一配置在配置文件中方便管理,这样但不支持动态动态修改,建议配置在zookeeper中,能够支持修改立即生效。
下面分析springboot默认支持的配置文件:
在分析监听器时,我们知道ConfigFileApplicationListener监听器是用来进行配置资源文件加载的,可以看到其实现了SmartApplicationListener类的supportsEventType方法,它对ApplicationEnvironmentPreparedEvent和ApplicationPreparedEvent两个事件进行了监听。

所以在环境准备的时候会去触发对应事件,所以在这个时候就会触发配置文件的加载

postProcessor.postProcessEnvironment(event.getEnvironment(),
event.getSpringApplication())这里会去进行属性值的加载

将RandomValuePropertySource添加到环境中支持Random类的随机数的配置
Loader(environment, resourceLoader).load()加载资源文件

这里面再看while里面的load方法

再看getSearchLocations()方法

首先看CONFIG_LOCATION_PROPERTY(spring.config.location)是否存在配置,无则走默认配置路径DEFAULT_SEARCH_LOCATIONS(classpath:/,classpath:/config/,file:./,file:./config/)然后遍历这四个目录下看是否存在application.properties/yml文件
names.forEach((name) -> load(location, name, profile, filterFactory, consumer)),names配置文件名称数组其实这里只有一个application(默认的配置文件名称),根据路径和名称进行配置文件的解析

这里的PropertySourceLoanders其实是在new Loader构建实例的时候设置的,也就是读取spring.factories文件配置中的PropertiesPropertySourceLoader和YamlPropertySourceLoader分别对properties和yaml文件的解析


两者覆写的load方法实现如何处理资源为PropertySource对象。
获取完文件后缀后调用loadIntoGroup方法将资源信息转化为PropertySource,其实质为调用PropertySourcesLoader中load方法
最后调用addConfigurationProperties(this.propertiesLoader.getPropertySources())方法将解析过后的资源信息放置进Enviroment中propertySources属性集合中
网友评论