Spring的表达式解析器模式(学习笔记_2022.07.22)
官网文档
简单使用例子
定义一个带变量的表达式, 返回值是布尔值
@Test
public void applicationTest() throws Throwable {
ExpressionParser expressionParser = new SpelExpressionParser();
// 如果表达式中需要使用字符串, 则用 '' 直接定义字段属性名称使用的是反射解析
Expression expression = expressionParser.parseExpression("goodsNum > 10 || goodsWeight > 30");
// 实体
GoodEntity entity = new GoodEntity();
entity.setGoodsNum(1);
entity.setGoodsWeight(2);
EvaluationContext context = new StandardEvaluationContext(entity);
Boolean value = expression.getValue(context,Boolean.class);
System.out.println("=================结果: "+value);
}
// =================结果: false
@Test
public void applicationTest() throws Throwable {
ExpressionParser expressionParser = new SpelExpressionParser();
// 如果表达式中需要使用字符串, 则用 ''
Expression expression = expressionParser.parseExpression("#goodsNum > 10 || #goodsWeight > 30");
// 不使用实体情况, 需要在表达式上字段属性名标注#字段名称
EvaluationContext context = new StandardEvaluationContext();
context.setVariable("goodsNum", 11);
context.setVariable("goodsWeight", 30);
Boolean value = expression.getValue(context, Boolean.class);
System.out.println("=================结果: " + value);
}
=================结果: true
跟踪了下源码, 表达式标注
#字段名称的 使用的是VariableReference取值不用
#字段名的情况下, 使用的是 PropertyOrFieldReference 取值 (通过ReflectivePropertyAccessor反射获取字段值, 大概意思就是只能使用自己定义的entity)
扩展
网上比较全的例子
1
版权声明:本文为weixin_44600430原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。