English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Spring SPEL Expressions

SpEL It is an extended language that supports querying and manipulating object graphs at runtime.

There are many available expression languages, such as JSP EL, OGNL, MVEL, and JBoss EL. SpEL provides some other features, such as method invocation and string template features.

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

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 examples

Let's see many useful SPEL examples. Here, we assume that all examples are written within the main() method.

Use the concat() method in conjunction with String

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

Convert the string to a 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]+" ");
}

Convert String to Bytes and Get Length

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

Convert String Content to Uppercase

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