Spring 表达语言的映射

2024-04-21

我想使用 SpEL 来评估一些谓词。由于值/属性是动态的,因此我没有特定的 bean 类。因此,我们有一个 hashmap,其中(根据应用程序状态)键映射到不同的 POJO/bean,例如:

Person person = new Person();// a person instance
person.setAge(25) // e.g. property age

Map<String, Object> model = new HashMap<>();
model.put("person", person);    
// and others ... 

我们希望通过设置变量来使用评估上下文,例如:

String predicate = "person.age>21";
StandardEvaluationContext context = new StandardEvaluationContext();
context.setVariables(model);
Expression expression = expressionParser.parseExpression(predicate);
boolean result = expression.getValue(context, Boolean.class);

但这会引发异常:

SpelEvaluationException:EL1007E:(pos 0):无法在 null 上找到属性或字段“person”

有人给建议吗?


由于该地图用于setVariables(), 你需要#person.age > 21 since person是一个变量。

或者您可以将地图设置为上下文的根对象。

context.setRootObject(model);

或者忘记上下文并将根对象传递给评估

expression.getValue(model, Boolean.class);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Spring 表达语言的映射 的相关文章

随机推荐