【SpEL】随机数
前言
- Spring Expression Language (SpEL)
- Spring Expression Version : 5.1.3.RELEASE
- Maven 3.6.3
- Eclipse Version: 2019-12 (4.14.0)
Eg
import org.junit.Assert; import org.springframework.expression.ExpressionParser; import org.springframework.expression.spel.standard.SpelExpressionParser;public class Test {public static void main(String[] args) {String exp = "T(java.lang.Math).random() * 100";ExpressionParser parser = new SpelExpressionParser();int randomNumber = parser.parseExpression(exp).getValue(Integer.class);Assert.assertTrue(randomNumber>=0 && randomNumber<100);} }測試隨機(jī)數(shù)
import org.junit.Assert; import org.springframework.expression.ExpressionParser; import org.springframework.expression.spel.standard.SpelExpressionParser;public class Test {public static void main(String[] args) {String exp = "T(java.lang.Math).random() * 100";ExpressionParser parser = new SpelExpressionParser();for (int i=0;i<10000;i++) {int randomNumber = parser.parseExpression(exp).getValue(Integer.class);Assert.assertTrue(randomNumber>=0 && randomNumber<100);} } }轉(zhuǎn)成 int
import org.junit.Assert; import org.springframework.expression.ExpressionParser; import org.springframework.expression.spel.standard.SpelExpressionParser;public class Test {public static void main(String[] args) {String exp = "T(Double).valueOf(T(java.lang.Math).random() * 100)";ExpressionParser parser = new SpelExpressionParser();int randomNumber = parser.parseExpression(exp).getValue(Integer.class);Assert.assertTrue(randomNumber>=0 && randomNumber<100);} }轉(zhuǎn)成 int 的另外一個方法
import org.junit.Assert; import org.springframework.expression.ExpressionParser; import org.springframework.expression.spel.standard.SpelExpressionParser;public class Test {public static void main(String[] args) {String exp = "new java.util.Random().nextInt(100)";ExpressionParser parser = new SpelExpressionParser();int randomNumber = parser.parseExpression(exp).getValue(Integer.class);Assert.assertTrue(randomNumber>=0 && randomNumber<100);} }應(yīng)用
將點(diǎn)擊量隨機(jī)翻2倍或3倍。
import org.junit.Assert; import org.springframework.expression.EvaluationContext; import org.springframework.expression.ExpressionParser; import org.springframework.expression.spel.standard.SpelExpressionParser; import org.springframework.expression.spel.support.StandardEvaluationContext;public class Test {public static void main(String[] args) {String exp = "#clickNum * (new java.util.Random().nextInt(2)+2)";int clickNum = 33;EvaluationContext context = new StandardEvaluationContext();context.setVariable("clickNum", clickNum); ExpressionParser parser = new SpelExpressionParser();int newClickNum = parser.parseExpression(exp).getValue(context, Integer.class);Assert.assertTrue(66==newClickNum || 99==newClickNum);} }參考
https://docs.spring.io/spring/docs/5.0.6.RELEASE/spring-framework-reference/core.html#expressions-types
總結(jié)
- 上一篇: 眼睛浮肿挂什么科
- 下一篇: 【spring-boot】启用数据缓存功