SpringCloud实现自定义属性文件加载
我们都知道SpringCloud 默认提供bootstrap文件加载,提供一个bootstrap context作为Spring Boot application context的parent,具体可以参考官方链接。
从SpringBoot2.4 版本之后,配置文件进行了重大变动,这个会对SpringCloud实现自定义属性文件加载实现有影响。
本文会以Spring Cloud 2020.0.0版本为例进行讲解,提供两种方式实现
- PropertySourceLocator实现 依赖以bootstrap context。这种方式实现有缺陷,具体可以参考官方issue
- ConfigDataLoader实现 基于new boot ConfigData framework
我们也可以参看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:{自定义前缀}: