前言
SpringBoot的默认的配置文件为application.properties或application.yml,本文讲解获取配置文件信息的方法。
Spring Boot使用非常特殊的PropertySource顺序,旨在允许合理地覆盖值。按以下顺序考虑属性:
- Devtools主目录上的全局设置属性(当devtools处于活动状态时~/.spring-boot-devtools.properties)。
- @TestPropertySource 测试上的注释。
- properties属于您的测试。可用于测试特定应用程序片段@SpringBootTest的 测试注释。
- 命令行参数。
- 来自SPRING_APPLICATION_JSON的属性(嵌入在环境变量或系统属性中的内联JSON)。
- ServletConfig init参数。
- ServletContext init参数。
- JNDI来自java:comp/env。
- Java系统属性(System.getProperties())。
- OS环境变量。
- RandomValuePropertySource仅在random.*中具有属性。
- 特定于配置文件的应用程序属性在打包的jar之外(application-{profile}.properties和YAML变体)。
- 打包在jar中的特定于配置文件的应用程序属性(application-{profile}.properties和YAML变体)。
- 打包jar之外的应用程序属性(application.properties和YAML变体)。
- 打包在jar中的应用程序属性(application.properties和YAML变体)。
- @PropertySource @Configuration 类上的注释。
- 默认属性(通过设置SpringApplication.setDefaultProperties指定)。
一、@Value绑定
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class UserConfig {
//美元表达式(从配置文件、系统环境变量读取)
@Value("${conf.test.string}")
private String stringTest;
@Value("${conf.test.integer}")
private Integer integerTest;
@Value("${conf.test.boolean}")
private Boolean booleanTest;
// 以默认值的形式赋予值, @Value默认必须要有配置项,配置项可以为空,但是必须要有,如果没有配置项,则可以给默认值
@Value("${conf.test.string:这是默认值}")
private String stringTestDefault;
@Value("${conf.test.integer:7900}")
private String integerTestDefault;
@Value("${conf.test.boolean:false}")
private Boolean booleanTestDefault;
}
conf:
test:
string: 字符测试
integer: 308943
boolean: true
二、@ConfigurationProperties
使用@ConfigurationProperties定义了配置文件配置参数的前缀,属性名称不要求一定相同,只需保证“set”字符串拼接配置文件的属性和setter方法名相同即可。
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Component
@ConfigurationProperties(prefix = "conf.auto")
public class UserAutoConf {
private String string;
private Integer integer;
private Boolean aboolean;
//集合
private List<String> hosts = new ArrayList<String>();
private String[] ports;
public String getString() {
return string;
}
public void setString(String string) {
this.string = string;
}
public Integer getInteger() {
return integer;
}
public void setInteger(Integer integer) {
this.integer = integer;
}
public Boolean getAboolean() {
return aboolean;
}
public void setAboolean(Boolean aboolean) {
this.aboolean = aboolean;
}
public List<String> getHosts() {
return hosts;
}
public void setHosts(List<String> hosts) {
this.hosts = hosts;
}
public String[] getPorts() {
return ports;
}
public void setPorts(String[] ports) {
this.ports = ports;
}
}
conf:
auto:
string: 字符测试
integer: 308943
aboolean: true
hosts[0]: 192.168.1.1
hosts[1]: 192.168.1.2
hosts[2]: 192.168.1.3
ports[0]: 8080
ports[1]: 8082
ports[2]: 8084
与@Value的比较
@ConfigurationProperties | @Value | |
---|---|---|
功能 | 批量注入配置文件中的属性 | 一个一个指定 |
松散绑定 | 支持 | 不支持 |
SpEL | 不支持 | 支持 |
JSR303数据校验 | 支持 | 不支持 |