弹簧表达语言的地图

时间:2017-05-14 18:48:25

标签: java spring spring-el

我想使用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'

有人建议吗?

1 个答案:

答案 0 :(得分:1)

由于地图用于setVariables(),因此#person.age > 21是变量,因此您需要person

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

context.setRootObject(model);

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

expression.getValue(model, Boolean.class);
相关问题