yml文件与properties文件
yml文件与properties文件同时存在时,优先使用properties的配置,其他配置进行互补
配置文件加载顺序
查找类ConfigFileApplicationListener 查看上面的注释
EnvironmentPostProcessor that configures the context environment by loading properties from well known file locations. By default properties will be loaded from ‘application.properties’ and/or ‘application.yml’ files in the following locations:(EnvironmentPostProcessor默认将从以下位置加载application.yml或application.properties文件)
- file:./config/ ( 项目根路径下的config文件夹)
- file:./config/*/ (这个 * 比如,我项目目录是/root, 这里就是代表/root/config/任意名称目录/
- file:./ (项目根路径)
- classpath:config/ (类资源路径下的config文件夹)
- classpath: (类资源路径下)
The list is ordered by precedence (properties defined in locations higher in the list override those defined in lower locations).Alternative search locations and names can be specified using setSearchLocations(String) and setSearchNames(String).(按优先级排序,列表中较高位置的会覆盖较低位置的属性)
Additional files will also be loaded based on active profiles. For example if a ‘web’ profile is active ‘application-web.properties’ and ‘application-web.yml’ will be considered.
The ‘spring.config.name’ property can be used to specify an alternative name to load and the ‘spring.config.location’ property can be used to specify alternative search locations or specific files.( 可以在命令行中使用选项"spring.config.name”属性可用于指定要加载的替代名称,“spring.config.location”属性可用于指定替代搜索位置或特定文件。)
Deprecated since 2.4.0 for removal in 2.6.0 in favor of configDataEnvironmentPostProcessor
Since:1.0.0
(1.0.0中出现,2.4.0中废弃,2.6.0中移除推荐使用ConfigDataEnvironmentPostProcessor)
然后我们查看ConfigDataEnvironmentPostProcessor类,会发现他跟ConfigDataEnvironment有关联,截取代码片段可以看到目录其实也是一样的
class ConfigDataEnvironment {
/**
* Default search locations used if not {@link #LOCATION_PROPERTY} is found.
*/
static final ConfigDataLocation[] DEFAULT_SEARCH_LOCATIONS;
static {
List<ConfigDataLocation> locations = new ArrayList<>();
locations.add(ConfigDataLocation.of("optional:classpath:/;optional:classpath:/config/"));
locations.add(ConfigDataLocation.of("optional:file:./;optional:file:./config/;optional:file:./config/*/"));
DEFAULT_SEARCH_LOCATIONS = locations.toArray(new ConfigDataLocation[0]);
}
}
配置优先级总结:file:./config/ ,file:./config/*/ ,file:./ ,classpath:/config/ ,classpath:/
具体可自行验证
除classpath下的配置文件会随jar包一起打包,其他几个路径下的配置文件不会,所以尽量使用classpath下的配置文件,其他的可以用作部署后统一配置一些地址