一、SpringBoot内置自动给配置赋值随机数
1.在application.properties中添加以下配置:
my.secret=${random.value} my.number=${random.int} my.bignumber=${random.long} my.uuid=${random.uuid} my.number.less.than.ten=${random.int(10)} my.number.in.range=${random.int [1024,65536]}
2.类中直接注入配置
packagecom.xing.studyboot.rest.controller; importorg.springframework.beans.factory.annotation.Value; importorg.springframework.web.bind.annotation.RequestMapping; importorg.springframework.web.bind.annotation.RestController; /*** 查看配置* @author xing* @createTime*/publicclassShowValueController { // @Value(value="${local.server.port}")// private String localServerPort;// // @Value(value="${spring.application.admin.enabled}")// private String springApplicationAdminEnabled;value="${my.secret}") (privateStringmySecret; value="${my.number}") (privateStringmyNumber; value="${my.bignumber}") (privateStringmyBignumber; value="${my.uuid}") (privateStringmyUUid; value="${my.number.less.than.ten}") (privateStringmyNumberLessThanTen; value="${my.number.in.range}") (privateStringmyNumberInRange; value="/showSome") (publicStringindex() { StringBuilderstr=newStringBuilder(); // str.append("本地端口local.server.port->"+localServerPort);// str.append("spring.application.admin.enabled->"+springApplicationAdminEnabled);str.append("my.secret->"+mySecret+"<br/>"); str.append("my.number->"+myNumber+"<br/>"); str.append("my.bignumber->"+myBignumber+"<br/>"); str.append("my.uuid->"+myUUid+"<br/>"); str.append("my.number.less.than.ten->"+myNumberLessThanTen+"<br/>"); str.append("my.my.number.in.range->"+myNumberInRange+"<br/>"); returnstr.toString(); } }
访问查看发现已自动生成了随机配置:
二、RandomValuePropertySource
1.源码
通过查看源码,可以看到我们只要传入不同类型的枚举name,即可获得name对应类型的随机数
/** Copyright 2012-2020 the original author or authors.** Licensed under the Apache License, Version 2.0 (the "License");* you may not use this file except in compliance with the License.* You may obtain a copy of the License at** https://www.apache.org/licenses/LICENSE-2.0** Unless required by applicable law or agreed to in writing, software* distributed under the License is distributed on an "AS IS" BASIS,* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.* See the License for the specific language governing permissions and* limitations under the License.*/packageorg.springframework.boot.env; importjava.util.Random; importjava.util.UUID; importorg.apache.commons.logging.Log; importorg.apache.commons.logging.LogFactory; importorg.springframework.core.env.ConfigurableEnvironment; importorg.springframework.core.env.MutablePropertySources; importorg.springframework.core.env.PropertySource; importorg.springframework.core.env.StandardEnvironment; importorg.springframework.core.log.LogMessage; importorg.springframework.util.DigestUtils; importorg.springframework.util.StringUtils; /*** {@link PropertySource} that returns a random value for any property that starts with* {@literal "random."}. Where the "unqualified property name" is the portion of the* requested property name beyond the "random." prefix, this {@link PropertySource}* returns:* <ul>* <li>When {@literal "int"}, a random {@link Integer} value, restricted by an optionally* specified range.</li>* <li>When {@literal "long"}, a random {@link Long} value, restricted by an optionally* specified range.</li>* <li>Otherwise, a {@code byte[]}.</li>* </ul>* The {@literal "random.int"} and {@literal "random.long"} properties supports a range* suffix whose syntax is:* <p>* {@code OPEN value (,max) CLOSE} where the {@code OPEN,CLOSE} are any character and* {@code value,max} are integers. If {@code max} is provided then {@code value} is the* minimum value and {@code max} is the maximum (exclusive).** @author Dave Syer* @author Matt Benson* @since 1.0.0*/publicclassRandomValuePropertySourceextendsPropertySource<Random> { /*** Name of the random {@link PropertySource}.*/publicstaticfinalStringRANDOM_PROPERTY_SOURCE_NAME="random"; privatestaticfinalStringPREFIX="random."; privatestaticfinalLoglogger=LogFactory.getLog(RandomValuePropertySource.class); publicRandomValuePropertySource() { this(RANDOM_PROPERTY_SOURCE_NAME); } publicRandomValuePropertySource(Stringname) { super(name, newRandom()); } publicObjectgetProperty(Stringname) { if (!name.startsWith(PREFIX)) { returnnull; } logger.trace(LogMessage.format("Generating random property for '%s'", name)); returngetRandomValue(name.substring(PREFIX.length())); } 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(); } privateStringgetRange(Stringtype, Stringprefix) { if (type.startsWith(prefix)) { intstartIndex=prefix.length() +1; if (type.length() >startIndex) { returntype.substring(startIndex, type.length() -1); } } returnnull; } privateintgetNextIntInRange(Stringrange) { String[] tokens=StringUtils.commaDelimitedListToStringArray(range); intstart=Integer.parseInt(tokens[0]); if (tokens.length==1) { returngetSource().nextInt(start); } returnstart+getSource().nextInt(Integer.parseInt(tokens[1]) -start); } privatelonggetNextLongInRange(Stringrange) { String[] tokens=StringUtils.commaDelimitedListToStringArray(range); if (tokens.length==1) { returnMath.abs(getSource().nextLong() %Long.parseLong(tokens[0])); } longlowerBound=Long.parseLong(tokens[0]); longupperBound=Long.parseLong(tokens[1]) -lowerBound; returnlowerBound+Math.abs(getSource().nextLong() %upperBound); } privateObjectgetRandomBytes() { byte[] bytes=newbyte[32]; getSource().nextBytes(bytes); returnDigestUtils.md5DigestAsHex(bytes); } publicstaticvoidaddToEnvironment(ConfigurableEnvironmentenvironment) { addToEnvironment(environment, logger); } staticvoidaddToEnvironment(ConfigurableEnvironmentenvironment, Loglogger) { MutablePropertySourcessources=environment.getPropertySources(); PropertySource<?>existing=sources.get(RANDOM_PROPERTY_SOURCE_NAME); if (existing!=null) { logger.trace("RandomValuePropertySource already present"); return; } RandomValuePropertySourcerandomSource=newRandomValuePropertySource(RANDOM_PROPERTY_SOURCE_NAME); if (sources.get(StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME) !=null) { sources.addAfter(StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME, randomSource); } else { sources.addLast(randomSource); } logger.trace("RandomValuePropertySource add to Environment"); } }
2.获取RandomValuePropertySource类的对象
在使用时,只要new 一个RandomValuePropertySource对象就可以使用以上源码中的各种方法了。两种构造的具体的差别,查了下也没查到,都能用。。。
// new 一个随机属性源newRandomValuePropertySource("myRandom"); // new 默认的随机属性源叫 random 等价于 new RandomValuePropertySource("random");newRandomValuePropertySource();
3.写法
packagecom.xing.studyboot.util; importorg.springframework.boot.env.RandomValuePropertySource; /*** 随机数工具类* 使用的时候 直接new获取* @author xing* @createTime 2021年5月11日 */publicclassRandomValueUtil { publicstaticvoidmain(String[] args) { // 自定义的一个随机值属性源,起名叫做 myRandomRandomValuePropertySourcerandom=newRandomValuePropertySource("myRandom"); // 随机生成一个整数System.out.println("random int:->"+random.getProperty("random.int")); // 随机生成一个整数,指定上边界,不大于等于5System.out.println("random int(5):->"+random.getProperty("random.int(5)")); // 使用()包围,2个字符 前闭后开=>比如 random.int(0,1)只能是0// 只要时两个符号就可以,不一定非要用()System.out.println("random int(0,1):->"+random.getProperty("random.int(0,1)")); System.out.println("random int(0,10):->"+random.getProperty("random.int(0,10)")); // ! 也行System.out.println("random int[0,1]:->"+random.getProperty("random.int!0,2!")); // !0,5& 也行System.out.println("random int[0,1]:->"+random.getProperty("random.int!0,5&")); // 前后各一个空格 也行 System.out.println("random int(1,3):->"+random.getProperty("random.int 1,3 ")); // 使用汉字包围,2个字符,前后各一个汉字 也行System.out.println("random int(3,4):->"+random.getProperty("random.int底3,4顶")); // 使用英文字母包围,2个字符,前后各一个英文字母 也行System.out.println("random int(5,6):->"+random.getProperty("random.intL5,6U")); // 使用数字包围,2个字符,前一个数字5,后一个数字6 也行System.out.println("random int(5,6):->"+random.getProperty("random.int55,66")); // 随机生成一个长整数 System.out.println("random long:->"+random.getProperty("random.long")); // 随机生成一个整数,使用区间[100,101),前闭后开=>只能是100System.out.println("random long(100,101):->"+random.getProperty("random.long(100,101)")); // 随机生成一个 uuidSystem.out.println("random uuid:->"+random.getProperty("random.uuid")); } }
好吧 费劲,直接看源码就能知道不管是啥字符,只要length对,就能获取,费了半天研究这个,没意思。。。
总结:
RandomValuePropertySource类通过实例化对象可以根据传入的type来返回对应的随机数。在配置中直接通过typename->比如${random.int(10)}可以直接自动赋值随机数给配置的key。
就这。。。