Spring Boot 是支持在系统加载的时候配置随机数的
1.添加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.创建类:
mport 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; } }
具体的生成细节可以参考Spring Boot的配置类:org.springframework.boot.context.config.RandomValuePropertySource
使用了 Java 自带的 java.util.Random 和 java.util.UUID 等工具类
public RandomValuePropertySource(String name) { super(name, new Random()); } 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(); }
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/18562.html