SpringBoot配置读取

133 阅读1分钟

外部配置文件

PropertySource

命令行参数

--spring.config.location=optional:classpath:cfg/* --spring.config.additional-location=optional:classpath:cfg/*

特定配置文件

application-dev.properties、application-prod.properties 根据spring.profiles.active的值来加载配置文件

导入其他配置文件

spring.config.import=optional:classpath:cfg/system.properties
#spring.config.import=optional:configtree:/run/secrets/ # 导入配置树

只会导入一次

定义配置加载(动态更新配置)

  1. 实现三个接口
    1. org.springframework.boot.context.config.ConfigDataLocationResolver 从配置文件解析出配置文件资源
    2. org.springframework.boot.context.config.ConfigDataResource 解析出配置
    3. org.springframework.boot.context.config.ConfigDataLoader 加载配置到spring中
  2. 配置到classpath:META-INF/spring.factories
org.springframework.boot.context.config.ConfigDataLocationResolver=xxx
org.springframework.boot.context.config.ConfigDataResource=xxx
org.springframework.boot.context.config.ConfigDataLoader=xxx

属性占位符

app.port=9999
app.url=http://localhost:${app.port}

多文档语法

yaml通过“---”分割,properties通过“#---”分割。 通常结合“spring.config.activate.on-profile”等类属性使用。 多文档配置无法通过PropertySource加载。

app.name=jonny1
#---
app.name=jonny2

激活属性

spring.config.activate.on-profile

spring.config.activate.on-cloud-platform

myprop=always-set
#---
spring.config.activate.on-cloud-platform=kubernetes
spring.config.activate.on-profile=prod | staging
myotherprop=sometimes-set

java -jar -Dspring.profiles.active=production demo-0.0.1-SNAPSHOT.jar

yaml读取

SpringBoot支持@Value读取yaml配置

# 可以直接使用random模块
test.uuid: ${random.uuid}

JavaBean绑定配置

ConfigurationProperties + EnableAutoConfiguration