Spring Boot 提供的org.springframework.boot.env.RandomValuePropertySource,可以很方便的生成随机数,可以生成integer、long、uuids及string类型的数据
示例代码
配置文件
demo.secret=${random.value}
demo.number=${random.int}
demo.bignumber=${random.long}
demo.uuid=${random.uuid}
demo.number.less.than.ten=${random.int(10)}
demo.number.in.range=${random.int[1024,65536]}
java代码
@Component
public class DemoCfgRandomValues {
private Logger logger= LoggerFactory.getLogger(this.getClass());
@Value("${demo.secret}")
private String secret;
@Value("${demo.number}")
private int number;
@Value("${demo.bignumber}")
private long bigNumber;
@Value("${demo.uuid}")
private String uuid;
@Value("${demo.number.less.than.ten}")
private int number2;
@Value("${demo.number.in.range}")
private int number3;
@PostConstruct
public void init(){
logger.info("Random demo.secret ===> {}",secret);
logger.info("Random number ===> {}",number);
logger.info("Random bigNumber ===> {}",bigNumber);
logger.info("Random uuid ===> {}",uuid);
logger.info("Random number2 ===> {}",number2);
logger.info("Random number3 ===> {}",number3);
}
运行结果
Random demo.secret ===> 036c8fc7cf82ed89a623e60d585bfd43
Random number ===> -139328813
Random bigNumber ===> 3041635784093814228
Random uuid ===> ea4cf2d1-a872-4f47-befe-89e79f3078ba
Random number2 ===> 1
Random number3 ===> 14996
备注
random.int*格式的是“前开后闭”原则
如:random.int(10),则生成10以内的整数,不包括10
random.int[1024,65536],生成大于等于1024,小于65536的整数。
random.value的值
生成的值是MD5加密然后再HEX编码的值,长度为32位。
可参考下面源代码
private Object getRandomValue(String type) {
if (type.equals("int")) {
return getSource().nextInt();
}
if (type.equals("long")) {
return getSource().nextLong();
}
String range = getRange(type, "int");
if (range != null) {
return getNextIntInRange(range);
}
range = getRange(type, "long");
if (range != null) {
return getNextLongInRange(range);
}
if (type.equals("uuid")) {
return UUID.randomUUID().toString();
}
return getRandomBytes();
}
private Object getRandomBytes() {
byte[] bytes = new byte[32];
getSource().nextBytes(bytes);
return DigestUtils.md5DigestAsHex(bytes);
}
网友评论