Spring Boot 配置随机数的技巧代码详解
SpringBoot支持在系统加载的时候配置随机数。
添加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]}
添加绑定类:
importorg.springframework.boot.context.properties.ConfigurationProperties;
importorg.springframework.context.annotation.PropertySource;
importorg.springframework.stereotype.Component;
@Component
@ConfigurationProperties(prefix="user.random")
@PropertySource(value={"config/random.properties"})
publicclassRandomConfig{
privateStringsecret;
privateintintNumber;
privateintlessTen;
privateintrange;
privatelonglongNumber;
privateStringuuid;
publicStringgetSecret(){
returnsecret;
}
publicvoidsetSecret(Stringsecret){
this.secret=secret;
}
publicintgetIntNumber(){
returnintNumber;
}
publicvoidsetIntNumber(intintNumber){
this.intNumber=intNumber;
}
publicintgetLessTen(){
returnlessTen;
}
publicvoidsetLessTen(intlessTen){
this.lessTen=lessTen;
}
publicintgetRange(){
returnrange;
}
publicvoidsetRange(intrange){
this.range=range;
}
publiclonggetLongNumber(){
returnlongNumber;
}
publicvoidsetLongNumber(longlongNumber){
this.longNumber=longNumber;
}
publicStringgetUuid(){
returnuuid;
}
publicvoidsetUuid(Stringuuid){
this.uuid=uuid;
}
}
输出如下:
secret=83a5c3402ef936a37842dc6de3d1af0f
intNumber=1816149855
lessTen=1
range=37625
longNumber=8449008776720010146
uuid=e5bc2091-1599-45b1-abd7-e3721ac77e6b
具体的生成细节可以参考SpringBoot的配置类:
org.springframework.boot.context.config.RandomValuePropertySource
来看下它的源码,实现其实很简单。
publicRandomValuePropertySource(Stringname){
super(name,newRandom());
}
privateObjectgetRandomValue(Stringtype){
if(type.equals("int")){
returngetSource().nextInt();
}
if(type.equals("long")){
returngetSource().nextLong();
}
Stringrange=getRange(type,"int");
if(range!=null){
returngetNextIntInRange(range);
}
range=getRange(type,"long");
if(range!=null){
returngetNextLongInRange(range);
}
if(type.equals("uuid")){
returnUUID.randomUUID().toString();
}
returngetRandomBytes();
}
其实就是使用了Java自带的java.util.Random和java.util.UUID等工具类,实现很简单,这里就不再详细解析了,大家可以自己去看下这个类的实现。
随机数的生成配置就是这么点了,我知道的是可以随机生成应用程序端口,其他的还真没用到。
总结
以上所述是小编给大家介绍的SpringBoot配置随机数技巧,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对毛票票网站的支持!