SpringBoot多种配置导入方式
在 Spring Boot 应用开发中,合理管理和加载配置是非常重要的。以往,我们通常使用 bootstrap.yaml/properties
方式来提前导入外部配置。但在 Spring Boot 2.4 及以上版本中,引入了 spring.config.import
机制,提供了更灵活的配置加载方式。
1. 传统的 bootstrap.yaml/properties
方式(Spring Boot 2.3 及以下)
在 Spring Boot 2.3 及以下版本,bootstrap.yaml
(或 bootstrap.properties
)主要用于加载外部配置,例如 Nacos。这种方式通常用于 Spring Cloud 组件初始化阶段。
示例:
1 | # bootstrap.yaml |
缺点:
bootstrap.yaml
与application.yaml
配置优先级不同,容易混淆。- 在 Spring Boot 2.4 及以上版本中已被
spring.config.import
取代。
2. spring.config.import
方式(Spring Boot 2.4+)
从 Spring Boot 2.4 开始,官方推荐使用 spring.config.import
来导入额外的配置源。
示例:
1 | # application.yaml |
注意事项:
- 如果使用
spring.config.import
,就不能使用bootstrap.yaml/properties
方式了; - 如果引入
spring-cloud-starter-alibaba-nacos-config
,但未使用spring.config.import
方式导入 Nacos 配置,Spring Boot 启动时会报错; - 可以通过
spring.cloud.nacos.config.import-check.enabled=false
关闭 Nacos 配置检查,但不推荐; - 想保留
bootstrap.yaml
方式,可以添加spring-cloud-starter-bootstrap
依赖。
1 | <dependency> |
3. 其他配置加载方式
通过 EnvironmentPostProcessor
代码方式动态加载配置
1 | public class CustomConfigLoader implements EnvironmentPostProcessor { |
然后在 META-INF/spring.factories
或 META-INF/spring/org.springframework.boot.env.EnvironmentPostProcessor
中注册:
1 | org.springframework.boot.env.EnvironmentPostProcessor=com.example.config.CustomConfigLoader |
通过 @PropertySource
读取自定义配置
1 |
|
通过命令行参数导入配置
1 | java -jar my-app.jar --spring.config.location=file:./config/custom-config.yaml |
4. 总结
方式 | 适用场景 | 适用版本 |
---|---|---|
bootstrap.yaml |
旧版本 Spring Cloud 配置加载 | 2.3 及以下 |
spring.config.import |
远程/本地额外配置导入 | 2.4+ |
EnvironmentPostProcessor |
动态加载配置 | 任意版本 |
@PropertySource |
读取额外配置文件 | 任意版本 |
命令行参数 | 临时指定配置路径 | 任意版本 |
从 Spring Boot 2.4 开始,spring.config.import
方式是官方推荐的配置加载方式,它比 bootstrap.yaml
更加灵活,也更容易理解。在不同的应用场景下,我们可以选择合适的方式来管理 Spring Boot 配置。
本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 沃特陌 | Wotemo!
评论