3
votes

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

1 Answers

2
votes

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);