Spring Boot支持在系统加载的时候配置随机数。
添加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]}
添加绑定类:
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;
@Component
@ConfigurationProperties(prefix = "user.random")
@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;
}
public int getRange() {
return range;
}
public void setRange(int range) {
this.range = range;
}
public long getLongNumber() {
return longNumber;
}
public void setLongNumber(long longNumber) {
this.longNumber = longNumber;
}
public String getUuid() {
return uuid;
}
public void setUuid(String uuid) {
this.uuid = uuid;
}
}
输出如下:
secret=83a5c3402ef936a37842dc6de3d1af0f
intNumber=1816149855
lessTen=1
range=37625
longNumber=8449008776720010146
uuid=e5bc2091-1599-45b1-abd7-e3721ac77e6b
具体的生成细节可以参考Spring Boot的配置类:
org.springframework.boot.context.config.RandomValuePropertySource
推荐阅读
分享Java干货,高并发编程,热门技术教程,微服务及分布式技术,架构设计,区块链技术,人工智能,大数据,Java面试题,以及前沿热门资讯等。