SpelExpressionParser example

In all my previous post under Spring SpEL, I was letting Spring framework to evaluate the SpEL expression when creating the Spring application context.

In addition to that we can manually evaluate a SpEL expression using SpelExpressionParser class.

This class is provided by Spring framework and below example shows how to use it.

Main class

package spel.package19;

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

public class Example19 {
    public static void main(String[] args) {
        SpelExpressionParser spelExpressionParser = new SpelExpressionParser();
        SpelExpression expression = spelExpressionParser.parseExpression("'Hello World'.concat('|')");
        String output = (String)expression.getValue();
        System.out.println(output);
    }
}

In the above code, at line 8, I create an instance of “SpelExpressionParser”.

At line 9, I parse an expression by passing the expression as argument to “parseExpression” method of “SpelExpressionParser” class.

The result of “parseExpression” method is an instance of “SpeLExpression” object which is assigned to “expression” variable. Refer to line 9

At line 10, we evaluate the expression by calling “getValue” method on “SpeLExpression” instance which is assigned to “expression” variable.

At line 11, we print the result of evaluation.

In this way we can manually evaluate an expression.

Leave a comment