Spring Boot.properties是否支持类似Play的多配置文件include功能
Spring Boot 多配置文件拆分引入方案说明
Spring Boot 原生的 .properties 标准语法本身没有内置和 Play Framework 完全一致的 include 关键字指令,但框架本身提供了多种能力完全等价的多配置拆分引入方案,可以实现按类别拆分、统一管理配置的需求,常用方案如下:
- 使用
spring.config.import配置(推荐,Spring Boot 2.4+ 版本支持)
这是最接近 Play Framework include 体验的方案,直接在主application.properties中通过该属性指定需要引入的配置文件即可,支持引入类路径文件、外部目录文件、配置中心配置等多种资源,导入的配置会按规则合并到Spring环境中,相同key的配置遵循Spring Boot标准优先级规则覆盖。
主配置示例:# 按顺序引入拆分的独立配置文件 spring.config.import=classpath:play-http.properties,\ classpath:play-modules.properties,\ classpath:play-i18n.properties,\ classpath:authentication.properties,\ classpath:hbase.properties,\ classpath:custom-caches.properties,\ classpath:custom-filters.properties # 其他根级别应用配置 - 使用
@PropertySource注解引入(适合自定义业务模块配置)
可以在Spring的配置类上通过该注解指定需要加载的properties文件,适合模块化引入自定义业务配置,示例:
注意:该方式加载的配置优先级低于主@Configuration @PropertySource(value = { "classpath:hbase.properties", "classpath:custom-caches.properties" }, ignoreResourceNotFound = false) public class CoreConfig { }application.properties,无法覆盖主配置中的同key值,也不能被日志系统等早于Spring上下文初始化的组件读取。 - 老版本兼容方案(Spring Boot 2.4 之前版本)
2.4之前的版本可以通过启动参数spring.config.additional-location指定额外的配置文件路径,或者结合profile特性使用spring.profiles.include引入对应profile组的配置文件,也能实现配置拆分的效果。
补充说明:如果习惯使用Play原生的include语法,也可以在Spring Boot中引入HOCON格式配置解析依赖,直接使用
.conf格式的配置文件,原生支持include指令,Spring Boot可以正常识别加载这类配置。
内容的提问来源于stack exchange,提问作者Bathiya Priyadarshana
相关产品推荐
相关产品推荐

