SpringBoot
允许你外置化项目的配置信息,你可以使用properties
文件、YAML
文件、环境变量、命令行参数来设置配置信息。
1 优先级
SpringBoot
提供多种外部配置方式,这些方式的优先级如下(由高到低):
- 命令行参数
- 来自
java:comp/env
的JNDI
属性 - Java系统属性(
System.getProperties()
) - 操作系统环境变量
RandomValuePropertySource
配置的random.*
属性值jar
包外部的application-{profile}.properties
或application.yml
(带spring.profile
)配置文件jar
包内部的application-{profile}.properties
或application.yml
(带spring.profile
)配置文件jar
包外部的application.properties
或application.yml
(不带spring.profile
)配置文件jar
包内部的application.properties
或application.yml
(不带spring.profile
)配置文件@Configuration
注解类上的@PropertySource
- 通过
SpringApplication.setDefaultProperties
指定的默认属性
2 使用
2.1 自定义配置
例如,在项目中定义一个类MyBean
,它的一个成员变量name
的值需要从外部配置文件中读取,可以使用@Value
注释:
@Component("myBean")
public class MyBean {
@Value("${MyBean.name}")
private String name;
}
${MyBean.name}
表示获取变量MyBean.name
的值,该变量可以在application.properties
文件中定义:
MyBean.name=MyBean-HaHa
2.2 使用SpringBoot提供的随机值
SpringBoot
内置了一个RandomValuePropertySource
类,提供了生成随机值的功能。我们可以在配置文件中或者代码中直接通过random.*
获取SpringBoot
提供的随机值。
random.value
—— 返回一个随机字符串random.int
—— 返回一个随机int
类型值random.long
—— 返回一个随机long
类型值random.uuid
—— 返回一个随机的uuid
random.int(10)
—— 返回一个小于10
的int
类型值random.int[1024, 65536]
—— 返回一个范围类的int
类型值
可以在application.properties
配置文件中获取并赋值给自定义的变量:
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]}
也可以直接在程序中取值:
@Component("myRandom")
public class MyRandom {
@Value("${random.value}")
//@Value("${my.secret}")
private String secret