SpringBoot允许将配置进行外部化(externalize),这样你就能够在不同的环境下使用相同的代码。你可以使用properties文件,yaml文件,环境变量和命令行参数来外部化配置。使用@Value注解,可以直接将属性值注入到beans中,然后通过Spring的Environment抽象或通过@ConfigurationProperties绑定到结构化对象来访问。
SpringBoot设计了一个非常特别的加载指定属性文件的顺序(@PropertySource),以允许对属性值进行合理的覆盖,属性会以如下的顺序进行设值:
home目录下的devtools全局设置属性(~/.spring-boot-devtools.properties,如果devtools激活)。
测试用例上的@TestPropertySource注解。
测试用例上的@SpringBootTest#properties注解。
命令行参数.
来自SPRING_APPLICATION_JSON的属性(环境变量或系统属性中内嵌的内联JSON)。
ServletConfig初始化参数。
ServletContext初始化参数。
来自于java:comp/env的JNDI属性。
Java系统属性(System.getProperties())。
操作系统环境变量。
RandomValuePropertySource,只包含random.*中的属性。
没有打进jar包的Profile-specific应用属性(application-{profile}.properties和YAML变量)。
打进jar包中的Profile-specific应用属性(application-{profile}.properties和YAML变量)。
没有打进jar包的应用配置(application.properties和YAML变量)。
打进jar包中的应用配置(application.properties和YAML变量)。
@Configuration类上的@PropertySource注解。
默认属性(使用SpringApplication.setDefaultProperties指定)。
1、配置随机值
SpringBoot支持在系统加载时配置生成随机数,比如生成密钥或用于测试时,是非常有用的。
(1)在src/main/resources/config/新建random.properties文件,添加内容如下:
#随机32位MD5字符串
user.random.secret=${random.value}
#随机int数字
user.random.intNumber=${random.int}
#随机long数字
user.random.longNumber=${random.long}
#随便uuid
user.random.uuid=${random.uuid}
#随机10以内的数字
user.random.lessTen=${random.int(10)}
#随机1024~65536之内的数字
user.random.range=${random.int[1024,65536]}
(2)新建配置绑定类
springboot/src/main/java/com/xcbeyond/springboot/config/RandomConfig.java
package com.xcbeyond.springboot.config;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
/**
* 随机数配置类
* @author xcbeyond
* 2018年7月11日下午3:04:12
*/
@Component
//绑定属性文件中的属性,prefix:属性前缀
@ConfigurationProperties(prefix="user.random")
//加载指定的属性配置文件,获取对应的key-value值,存储到Spring的Environment中
@PropertySource(value="config/random.properties")
public class RandomConfig {
private String secret;
private int intNumber;
private int lessTen;
private int range;
private long longNumber;
private String uuid;
public String getSecret() {
return secret;
}
public void setSecret(String secret) {
this.secret = secret;
}
public int getIntNumber() {
return intNumber;
}
public void setIntNumber(int intNumber) {
this.intNumber = intNumber;
}
public int getLessTen() {
return lessTen;
}
public void setLessTen(int lessTen) {
this.lessTen = lessTen;
}
SpringBoot特性_外部化配置(properties文件配置)
最新推荐文章于 2023-04-05 19:36:53 发布