外部化配置
Spring Boot允许您外部化配置,以便您可以在不同的环境中使用相同的应用程序代码。您可以使用properties文件,YAML文件,环境变量和命令行参数来外部化配置。
属性值可以通过@Value
注解直接注入到你的Bean ,通过Spring的Environment
抽象访问,或者通过@ConfigurationProperties
绑定到结构化对象。
Spring Boot使用一种非常特殊的PropertySource
顺序,旨在允许合理地覆盖值。按以下顺序考虑属性:
这里只列出常用的
- 命令行参数。
- 来自
SPRING_APPLICATION_JSON
(嵌入在环境变量或系统属性中的内联JSON)的属性。 - Java系统属性(
System.getProperties()
)。 - OS环境变量。
-
RandomValuePropertySource
产生随机值函数的方法源random.*
。 - 打包jar之外或之内的应用程序属性(
application.properties
以及application.yml
)。 -
@PropertySource
你的@Configuration
注解上的类的属性配置。 - 默认属性(由设置指定
SpringApplication.setDefaultProperties
)。
属性取值示例:
import org.springframework.stereotype.*;
import org.springframework.beans.factory.annotation.*;
@Component
public class MyBean {
@Value("${name}")
private String name;
// ...
}
命令行设置属性
$ java -Dspring.application.json='{"name":"test"}' -jar myapp.jar
$ java -jar myapp.jar --spring.application.json='{"name":"test"}'
配置随机值
my.secret=${random.value}
my.number=${random.int}
my.bignumber=${random.long}
my.uuid=${random.uuid}
my.number.less.than.ten=${random.int(10)}
my.number.in.range=${random.int[1024,65536]}
服务器端口配置:server.port=80
application.properties可在位置
- 一个/config当前目录的子目录
- 当前目录
- 一个classpath /config包
- 类路径根
列表按优先级排序
(在列表中较高位置定义的属性将覆盖在较低位置中定义的属性)
如果您不喜欢application.properties配置文件名,可以通过指定spring.config.name环境属性切换到另一个文件名。
属性中的占位符
使用时,值application.properties将通过现有值进行过滤Environment ,因此您可以返回先前定义的值(例如,从“系统”属性)
app.name=MyApp
app.description=${app.name} is a Spring Boot application
YAML和properties互换
yml:
environments:
dev:
url: https://dev.example.com
name: Developer Setup
prod:
url: https://another.example.com
name: My Cool App
my:
servers:
- dev.example.com
- another.example.com
properties:
environments.dev.url=https://dev.example.com
environments.dev.name=Developer Setup
environments.prod.url=https://another.example.com
environments.prod.name=My Cool App
my.servers[0]=dev.example.com
my.servers[1]=another.example.com
使用@PropertySource注释无法加载YAML文件。因此,如果您需要以这种方式加载值,则需要使用属性文件。
其他方式
- 类型安全配置属性
- 第三方配置
- 轻松绑定
- 合并复杂类型
- 属性转换
- @ConfigurationProperties验证
- @ConfigurationProperties与@Value
- 隔离应用程序配置
- 添加活动配置文件
- 以编程方式设置配置文件
返回目录
网友评论