Let's say we have the following code snippet, that fills a list with several prime numbers and defines it as a variable in a SpEL context:
// create an array of integers
List<Integer> primes = new ArrayList<Integer>();
primes.addAll(Arrays.asList(2,3,5,7,11,13,17));
// create parser and set variable 'primes' as the array of integers
ExpressionParser parser = new SpelExpressionParser();
StandardEvaluationContext ctx = new StandardEvaluationContext();
ctx.setVariable("primes", primes);
Now, if we want to narrow the list and get all the prime numbers that are > 10, we can use the ?[]
selection operator. The statement would be this one:
Expression expression = parser.parseExpression("#primes.?[#this>10]");
List<Integer> primesGreaterThanTen = (List<Integer>) expression.getValue(ctx);
As you can see, the expression to be evaluated is #primes.?[#this > 10]
. How does it work ?
#primes
refers to theprimes
list.- The
?[]
selection operator matches every objecti
in theprimes
list which is not null and which matches the criteria, given in the brackets. In our example, the criteria is#this > 10
.#this
refers to the current evaluation object, which in our example would be the object from the list that is being checked at the moment for not-null and > 10.
The result from the evaluation will be a list, containing:
[11, 13, 17]
A SpEL context can have a #root
variable. Let's have this simple class:
public class SomeCustomObject {
public int stringLength(String input) {
if (input == null) return 0;
return input.length();
}
}
and define a instance of our SomeCustomObject
as the #root
variable.
SomeCustomObject someObject = new SomeCustomObject();
context.setRootObject(someObject);
This will create the someObject
variable a root object for the SpEL context.
A simple example with the #root
variable.
String name = "kocko";
ctx.setVariable("name", kocko);
String statement = "#root.stringLength(#kocko) == 5";
Expression expression = parser.parseExpression(statement);
boolean result = expression.getValue(context, Boolean.class);
The result
variable will be evaluated as true
.
What is the power of the #root
?
Through a single root object, you can expose a comprehensive, custom environment to your expressions, for example custom utility methods and/or variables.
More info: