spring配置文件加载顺序

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文件

  1. file:./config/ ( 项目根路径下的config文件夹)
  2. file:./config/*/ (这个 * 比如,我项目目录是/root, 这里就是代表/root/config/任意名称目录/
  3. file:./ (项目根路径)
  4. classpath:config/ (类资源路径下的config文件夹)
  5. 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下的配置文件,其他的可以用作部署后统一配置一些地址

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值