<profiles>
<profile>
<!-- 配置id -->
<id>test</id>
<activation>
<!-- 是否启用为默认的配置 -->
<activeByDefault>true</activeByDefault>
</activation>
<!-- 其他参数 -->
<properties>
<env>test</env>
</properties>
</profile>
</profiles>
<build>
<!-- maven 打包时需要加载的resource目录配置 -->
<resources>
<resource>
<!-- 配置resource目录 -->
<directory>src/main/resources</directory>
<!-- 需要排除的目录 -->
<excludes>
<exclude>dev/*</exclude>
<exclude>prod/*</exclude>
<exclude>test/*</exclude>
</excludes>
</resource>
<resource>
<!--根据不同的环境,把对应文件夹里的配置文件打包-->
<directory>src/main/resources/${env}</directory>
<!-- 配置导出的文件路径 -->
<targetPath>/new</targetPath>
</resource>
</resources>
</build>
源码地址
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot</artifactId>
<version>2.0.5.RELEASE</version>
</dependency>
业务类 org.springframework.boot.context.config.ConfigFileApplicationListener
入口方法:onApplicationEvent(ApplicationEvent event)
项目启动后发布事件ApplicationEvent
,触发配置文件监听器加载配置
读取配置
方法:load()
开始读取配置
初始化环境 profile
方法:initializeProfiles()
根据 spring.profiles.active 和 spring.profiles.include 加载相关的配置
读取各个location的文件
方法:load(Profile profile, DocumentFilterFactory filterFactory,
DocumentConsumer consumer)
读取各个location的文件
读取所有路径
方法:getSearchLocations()
如果 environment 里包含 spring.config.location,则从对应的路径去读取配置文件
如果没有配,则从classpath:/,classpath:/config/,file:./,file:./config/ 倒序去获取
读取所有配置文件名称
方法:getSearchNames()
如果 environment 里包含 spring.config.name ,则读取对应的配置文件
如果没有,则依次加载:bootstrap、application
使用各个loader去读取
方法:load(String location, String name, Profile profile,
DocumentFilterFactory filterFactory, DocumentConsumer consumer)
使用所有的loader遍历读取配置
加载所有的loader
是在初始化Loader
的时候加载的
实例化 Loader
new Loader(environment, resourceLoader)
加载各个 propertySourceLoader
读取 Loader
到 propertySourceLoaders
方法:SpringFactoriesLoader.loadFactories(PropertySourceLoader.class, getClass().getClassLoader())
默认读取到 YamlPropertySourceLoader 和 PropertiesPropertySourceLoader
其中 YamlPropertySourceLoader 可以配置 "yml", "yaml"
其中 PropertiesPropertySourceLoader 可以配置 "properties", "xml"
读取所有的 propertySourceLoader
方法: loadFactoryNames(factoryClass, classLoaderToUse)
读取 factoryClass 的所有实现类
追加环境后缀
方法:loadForFileExtension(PropertySourceLoader loader, String prefix,String fileExtension, Profile profile,DocumentFilterFactory filterFactory, DocumentConsumer consumer)
如果有启用的环境,则加载配置文件时候加载对应环境后缀的配置
读取配置
方法:load(PropertySourceLoader loader, String location, Profile profile, DocumentFilter filter, DocumentConsumer consumer)
挨个加载配置文件内的属性
SpringBoot Maven 项目启用默认配置文件 源码解读
原文:https://www.cnblogs.com/ant007/p/14746033.html