Map for spring expression language

懵懂的女人 提交于 2019-12-23 03:07:25

问题


I want to use SpEL to evaluate some predicates. Since the values/properties are dynamic, I don't have a certain bean class. Therefore, we have a hashmap where (according to the appliction state) the keys map to different POJOs/beans, e.g.:

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 ... 

We expected to use the Evaluation Context for this by setting the variables, like:

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

But this throws an exception:

SpelEvaluationException: EL1007E:(pos 0): Property or field 'person' cannot be found on null

Anyone an advice?


回答1:


Since the map is used in setVariables(), you need #person.age > 21 since person is a variable.

Or you can set the map as the root object of the context.

context.setRootObject(model);

Or forget the context and pass the root object to the evaluation

expression.getValue(model, Boolean.class);


来源:https://stackoverflow.com/questions/43967629/map-for-spring-expression-language

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!