”;
ExpressionParser is the main interface of Spring SpEL which helps parsing expression strings into compiled expressions. These compiled expressions can be evaluated and supports parsing templates as well as standard expression string.
Syntax
Following is an example of creating an ExpressionParser and using its object to get a value.
ExpressionParser parser = new SpelExpressionParser(); Expression exp = parser.parseExpression("''Welcome to Tutorialspoint''"); String message = (String) exp.getValue();
It should print the result as follows −
Welcome to Tutorialspoint
-
ExpressionParser − An interface responsible to parse an expression string.
-
Expression − An interface responsible to evaluate an expression string.
-
Exceptions − ParseException and EvaluationException can be thrown during parseExpression and getValue method invokation.
SpEL supports calling methods, calling constructors and accessing properties. Following example shows the various use cases.
Example
The following example shows a class MainApp.
Let”s update the project created in Spring SpEL – Create Project chapter. We”re adding following files −
-
MainApp.java − Main application to run and test.
Here is the content of MainApp.java file −
package com.tutorialspoint; import org.springframework.expression.Expression; import org.springframework.expression.ExpressionParser; import org.springframework.expression.spel.standard.SpelExpressionParser; public class MainApp { public static void main(String[] args) { ExpressionParser parser = new SpelExpressionParser(); // parse a plain text Expression exp = parser.parseExpression("''Welcome to tutorialspoint''"); String message = (String) exp.getValue(); System.out.println(message); // invoke a method exp = parser.parseExpression("''Welcome to tutorialspoint''.concat(''!'')"); message = (String) exp.getValue(); System.out.println(message); // get a property exp = parser.parseExpression("''Welcome to tutorialspoint''.bytes"); byte[] bytes = (byte[]) exp.getValue(); System.out.println(bytes.length); // get nested properties exp = parser.parseExpression("''Welcome to tutorialspoint''.bytes.length"); int length = (Integer) exp.getValue(); System.out.println(length); //Calling constructor exp = parser.parseExpression("new String(''Welcome to tutorialspoint'').toUpperCase()"); message = (String) exp.getValue(); System.out.println(message); } }
Output
Welcome to tutorialspoint Welcome to tutorialspoint! 25 25 WELCOME TO TUTORIALSPOINT
”;