Spring Expression Language (SPEL) Tutorial

The Spring Expression Language (SpEL for short) is a powerful expression language that supports querying and manipulating an object graph at runtime. The language syntax is similar to Unified EL but offers additional features, most notably method invocation and basic string templating functionality.

While there are several other Java expression languages available, OGNL, MVEL, and JBoss EL, to name a few, the Spring Expression Language was created to provide the Spring community with a single well supported expression language that can be used across all the products in the Spring portfolio.

SpEL API

The SpEL API provides many interfaces and classes. They are as follows:

  • Expression interface
  • SpelExpression class
  • ExpressionParser interface
  • SpelExpressionParser class
  • EvaluationContext interface
  • StandardEvaluationContext class

Feature Overview

  • Literal expressions
  • Boolean and relational operators
  • Regular expressions
  • Class expressions
  • Accessing properties, arrays, lists, maps
  • Method invocation
  • Relational operators
  • Assignment
  • Calling constructors
  • Bean references
  • Array construction
  • Inline lists
  • Inline maps
  • Ternary operator
  • Variables
  • User defined functions
  • Collection projection
  • Collection selection
  • Templated expressions

Hello SPEL Example

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

public class Test {
public static void main(String[] args) {
ExpressionParser parser = new SpelExpressionParser();

Expression exp = parser.parseExpression("'Hello SPEL'");
String message = (String) exp.getValue();
System.out.println(message);
//OR
//System.out.println(parser.parseExpression("'Hello SPEL'").getValue());
}
}

Other SPEL Example

Let's see a lot of useful examples of SPEL. Here, we are assuming all the examples have been written inside the main() method.

Using concat() method with String

ExpressionParser parser = new SpelExpressionParser();
Expression exp = parser.parseExpression("'Welcome SPEL'.concat('!')");
String message = (String) exp.getValue();
System.out.println(message);

Converting String into byte array

Expression exp = parser.parseExpression("'Hello World'.bytes");
byte[] bytes = (byte[]) exp.getValue();
for(int i=0;i<bytes.length;i++){
	System.out.print(bytes[i]+" ");
}

Getting length after converting string into bytes

Expression exp = parser.parseExpression("'Hello World'.bytes.length");
int length = (Integer) exp.getValue();
System.out.println(length);

Converting String contents into uppercase letter

Expression exp = parser.parseExpression("new String('hello world').toUpperCase()");
String message = exp.getValue(String.class);
System.out.println(message);
//OR
System.out.println(parser.parseExpression("'hello world'.toUpperCase()").getValue());