SpringCloud 实现自定义属性文件加载

本文介绍了在Spring Cloud 2020.0.0版本下,如何实现自定义属性文件加载。通过PropertySourceLocator和ConfigDataLoader两种方式进行演示,详细阐述了实现步骤并提供了demo。SpringBoot2.4后的配置文件变动对实现自定义加载有一定影响。总结中提到,从该版本开始,外部配置文件加载主要依赖ConfigDataLoader。
摘要由CSDN通过智能技术生成

SpringCloud实现自定义属性文件加载

我们都知道SpringCloud 默认提供bootstrap文件加载,提供一个bootstrap context作为Spring Boot application context的parent,具体可以参考官方链接
从SpringBoot2.4 版本之后,配置文件进行了重大变动,这个会对SpringCloud实现自定义属性文件加载实现有影响。
在这里插入图片描述
本文会以Spring Cloud 2020.0.0版本为例进行讲解,提供两种方式实现

我们也可以参看spring cloud config client 项目中的实现,具体类如下:

  • ConfigServerConfigDataLoader 基于ConfigDataLoader实现
  • ConfigServicePropertySourceLocator 基于PropertySourceLocator实现

基于PropertySourceLocator实现

实现步骤

  • 实现PropertySourceLocator
  • 在META-INF/spring.factories 的配置:
org.springframework.cloud.bootstrap.BootstrapConfiguration=${PropertySourceLocator 实现类}
  • pom.xml 引入spring-cloud-starter-bootstrap或者环境变量/系统变量设置spring.cloud.bootstrap.enabled=true,具体可以参考

demo

@Configuration
public class CustomPropertySourceLocator implements PropertySourceLocator {
   

    @Override
    public PropertySource<?> locate(Environment environment) {
   
        return new MapPropertySource("customProperty",
                Collections.<String, Object>singletonMap("property.from.sample.custom.source", "worked as intended"));
    }

}

基于ConfigDataLoader 实现

实现步骤

  • 实现ConfigDataLoader、ConfigDataLocationResolver、ConfigDataResource
  • 在META-INF/spring.factories 的配置:
org.springframework.boot.context.config.ConfigDataLocationResolver=\
${ConfigDataLocationResolver实现类}
org.springframework.boot.context.config.ConfigDataLoader=\
${ConfigDataLoader实现类}
  • 在application配置 spring.config.import=optional:{自定义前缀}:

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值