Expression Evaluation using Spring’s Expression Interface

ExpressionParser parses expression strings into compiled expressions that can be evaluated. It also supports parsing templates as well as standard expression strings.

Following code demonstrates few examples of “ExpressionParser” interface.

package com.kruders.core;

import org.springframework.expression.EvaluationContext;
import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;

import com.kruders.bean.Employee;

public class Main {
	public static void main(String[] args) {
		ExpressionParser parser = new SpelExpressionParser();
		Expression exp = parser.parseExpression("'Hello World!!!'");
		String result = exp.getValue(String.class); 
		System.out.println("String " + result);
		Employee emp = new Employee("Puneet");
		EvaluationContext context = new StandardEvaluationContext(emp);
		Expression exp1 = parser.parseExpression("name");
		String name = (String) exp1.getValue(context);
		System.out.println("Name " + name);
		Expression exp2 = parser.parseExpression("name == 'Puneet'");
		Boolean checkName = exp2.getValue(context, Boolean.class);
		System.out.println("\"name == Puneet ?\" is " + checkName);
You can download the source code of this example here.

, , ,

No comments yet.

Leave a Reply