In this post under Spring SpEL, I will explain with example how to make java objects available to SpElExpression during its evaluation.
For our example we will use the below pojo class
Employee
package spel.package20;
public class Employee {
private int id;
private String name;
private int salary;
public Employee(int id, String name, int salary) {
this.id = id;
this.name = name;
this.salary = salary;
}
//Getter and Setter are removed for brevity
}
Below is the main class that shows how to make the “Employee” object available for SpEl expression.
1 package spel.package20;
2
3 import org.springframework.expression.Expression;
4 import org.springframework.expression.spel.standard.SpelExpressionParser;
5
6 public class Example20 {
7 public static void main(String[] args) {
8 Employee employee = new Employee(1, "John Doe", 1000);
9
10 SpelExpressionParser spelExpressionParser = new SpelExpressionParser();
11 Expression expression = spelExpressionParser.parseExpression("name != null");
12 boolean result = expression.getValue(employee, Boolean.class);
13 System.out.println(result);
14
15 employee.setName(null);
16 result = expression.getValue(employee, Boolean.class);
17 System.out.println(result);
18 }
19 }
In the above main class, at line 8, I created an “Employee” object.
At line 10, I created an instance of “SpElExpressionParser”.
At line 11, I created an spel expression “name != null”.
Then created an instance of “Expression” class by calling “parseExpression” on “SpElExpressionParser” instance and passed the expression “name != null” as an argument.
By seeing the expression “name != null”, we come to conclusion that we are verifying whether the variable “name” is null or not.
But what this variable “name” refers to. Is it standalone variable or property of an object. The SpEL doesn’t know. So we have to provide context.
This is achieved by calling overloaded “getValue” method on “Expression” instance. This method takes two parameters
1) passing the employee object as context
2) result data type.
The “Expression” object resolves the variable “name” with the property “name” in the “employee” object and checks whether the property is null or not and returns the result.
In this way, we can make java objects be available for a spel expression evaluation.