Spring SpEL - Quick Guide



Spring SpEL - Overview

The Spring Expression Language, SpEL is a very powerful expression language and it supports querying and manipulating an object graph at runtime. It offers many advanced features like method invocation and basic string templating functionality.

Spring Expression Language was originally created for the Spring community to have a single well supported expression language to be used across all the products in the Spring portfolio. While SpEL serves as the foundation for expression evaluation within the Spring portfolio, it is not directly tied to Spring and can be used independently.

Functionalities supported by SpEL

Following is the list of functionalities that Spring Expression Language, SpEL supports −

  • 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

  • Ternary operator

  • Variables

  • User defined functions

  • Collection projection

  • Collection selection

  • Templated expressions

We'll cover each and every topic in next chapters.

Spring SpEL - Environment Setup

This chapter will guide you on how to prepare a development environment to start your work with Spring and its SpEL Capabilities. It will also teach you how to set up JDK on your machine before you set up spring −

Setup Java Development Kit (JDK)

You can download the latest version of SDK from Oracle's Java site − Java SE Downloads. You will find instructions for installing JDK in downloaded files, follow the given instructions to install and configure the setup. Finally set PATH and JAVA_HOME environment variables to refer to the directory that contains java and javac, typically java_install_dir/bin and java_install_dir respectively.

If you are running Windows and have installed the JDK in C:\jdk-24, you would have to put the following line in your C:\autoexec.bat file.

set PATH=C:\jdk-24;%PATH% 
set JAVA_HOME=C:\jdk-24

Alternatively, on Windows NT/2000/XP, you will have to right-click on My Computer, select Properties → Advanced → Environment Variables. Then, you will have to update the PATH value and click the OK button.

On Unix (Solaris, Linux, etc.), if the SDK is installed in /usr/local/jdk-24 and you use the C shell, you will have to put the following into your .cshrc file.

setenv PATH /usr/local/jdk-24/bin:$PATH 
setenv JAVA_HOME /usr/local/jdk-24

Alternatively, if you use an Integrated Development Environment (IDE) like Borland JBuilder, Eclipse, IntelliJ IDEA, or Sun ONE Studio, you will have to compile and run a simple program to confirm that the IDE knows where you have installed Java. Otherwise, you will have to carry out a proper setup as given in the document of the IDE.

Popular Java Editors

To write your Java programs, you need a text editor. There are many sophisticated IDEs available in the market. But for now, you can consider one of the following −

  • Notepad − On Windows machine, you can use any simple text editor like Notepad (Recommended for this tutorial), TextPad.

  • Netbeans − It is a Java IDE that is open-source and free, which can be downloaded from www.netbeans.org/index.html.

  • Eclipse − It is also a Java IDE developed by the eclipse open-source community and can be downloaded from www.eclipse.org.

Install Eclipse

In this chapter, we will explain how to set Spring environment in Eclipse IDE. Before proceeding with the installation, make sure that you already have Eclipse installed in your system. If not, download and install Eclipse.

For more information on Eclipse, please refer our Eclipse Tutorial

Step 2: Create a Maven project and set build path

Open eclipse and create a Maven based project as shown below.

New Maven Project

Update the pom.xml as shown below to include spring framework libraries. Rest eclipse will handle automatically.

Pom.xml for Spring

open the pom.xml and paste the following content in it and refresh the project.

<project xmlns="http://maven.apache.org/POM/4.0.0" 
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
   xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
   <modelVersion>4.0.0</modelVersion>
   <groupId>com.tutorialspoint</groupId>
   <artifactId>springspel</artifactId>
   <version>0.0.1-SNAPSHOT</version>
   <name>springdi</name>
   <description>Spring Dependency Injection Project</description>
   <properties>
      <java.version>24</java.version>
      <spring.version>7.0.0-M9</spring.version>
   </properties>
   <build>      
      <plugins>
         <plugin>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.7.0</version>
            <configuration>
               <source>${java.version}</source>
               <target>${java.version}</target>
            </configuration>
         </plugin>
      </plugins>
   </build>
   <dependencies>
      <dependency>
         <groupId>org.springframework</groupId>
         <artifactId>spring-core</artifactId>
         <version>${spring.version}</version>
      </dependency>
      <dependency>
         <groupId>org.springframework</groupId>
         <artifactId>spring-context</artifactId>
         <version>${spring.version}</version>
      </dependency>
      <dependency>
         <groupId>org.springframework</groupId>
         <artifactId>spring-aspects</artifactId>
         <version>${spring.version}</version>
      </dependency>
      <dependency>
         <groupId>jakarta.annotation</groupId>
         <artifactId>jakarta.annotation-api</artifactId>
         <version>2.1.1</version> 
      </dependency>
   </dependencies>
</project>

Spring SpEL - Create Project

Create a New Project

Using eclipse, select FileNew Maven Project. Tick the Create a simple project(skip archetype selection) and click Next.

Enter the details, as shown below −

  • groupId − com.tutorialspoint

  • artifactId − springspel

  • version − 0.0.1-SNAPSHOT

  • name − springdi

  • description − Spring SpEL Project

Click on Finish button and an new project will be created.

pom.xml

Update the pom.xml with Spring Core dependency. Following is the full content of pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" 
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
   xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
   <modelVersion>4.0.0</modelVersion>
   <groupId>com.tutorialspoint</groupId>
   <artifactId>springspel</artifactId>
   <version>0.0.1-SNAPSHOT</version>
   <name>springspel</name>
   <description>Spring SpEL Project</description>
   <properties>
      <java.version>24</java.version>
      <spring.version>7.0.0-M9</spring.version>
   </properties>
   <build>      
      <plugins>
         <plugin>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.7.0</version>
            <configuration>
               <source>${java.version}</source>
               <target>${java.version}</target>
            </configuration>
         </plugin>
      </plugins>
   </build>
   <dependencies>
      <dependency>
         <groupId>org.springframework</groupId>
         <artifactId>spring-core</artifactId>
         <version>${spring.version}</version>
      </dependency>
      <dependency>
         <groupId>org.springframework</groupId>
         <artifactId>spring-context</artifactId>
         <version>${spring.version}</version>
      </dependency>
      <dependency>
         <groupId>org.springframework</groupId>
         <artifactId>spring-aspects</artifactId>
         <version>${spring.version}</version>
      </dependency>
      <dependency>
         <groupId>jakarta.annotation</groupId>
         <artifactId>jakarta.annotation-api</artifactId>
         <version>2.1.1</version> 
      </dependency>
   </dependencies>
</project>

applicationcontext.xml

Create applicationcontext.xml in src → main → resources with the following content.

<?xml version="1.0" encoding="UTF-8"?>  
<beans xmlns="http://www.springframework.org/schema/beans"  
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   
   xsi:schemaLocation="http://www.springframework.org/schema/beans   
   http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">  
</beans> 

Spring SpEL - ExpressionParser Interface

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

Where

  • 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 - Usage of ExpressionParser

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.

MainApp.java

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

Once you are done creating the source and bean configuration files, let us run the application. If everything is fine with your application, it will print the following message −

Welcome to tutorialspoint
Welcome to tutorialspoint!
25
25
WELCOME TO TUTORIALSPOINT

Spring SpEL - EvaluationContext Interface

EvaluationContext is an interface of Spring SpEL which helps to execute an expression string in a context. References are resolved in this context when encountered during expression evaluation.

Syntax

Following is an example of creating an EvaluationContext and using its object to get a value.

ExpressionParser parser = new SpelExpressionParser();
Expression exp = parser.parseExpression("'name'");
EvaluationContext context = new StandardEvaluationContext(employee);
String name = (String) exp.getValue();

It should print the result as follows −

Mahesh

Here the result is the value of the name field of the employee object, Mahesh. The StandardEvaluationContext class specifies the object against which the expression is evaluated. StandardEvaluationContext cannot be changed once context object is created. It caches the state and allows expression evaluation to be performed quickly. Following example shows the various usecases.

Example - Usage of EvaluationContext

The following example shows a class MainApp.

Let's update the project created in Spring SpEL - Create Project chapter. We're adding/updating following files −

  • Employee.java − Employee class.

  • MainApp.java − Main application to run and test.

Employee.java

Here is the content of Employee.java file −

package com.tutorialspoint;

public class Employee {
   private int id;
   private String name;
   public int getId() {
      return id;
   }
   public void setId(int id) {
      this.id = id;
   }
   public String getName() {
      return name;
   }
   public void setName(String name) {
      this.name = name;
   }
}

MainApp.java

Here is the content of MainApp.java file −

package com.tutorialspoint;

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

public class MainApp {
   public static void main(String[] args) {
      Employee employee = new Employee();
      employee.setId(1);
      employee.setName("Mahesh");

      ExpressionParser parser = new SpelExpressionParser();
      EvaluationContext context = new StandardEvaluationContext(employee);
      Expression exp = parser.parseExpression("name");
      
      // evaluate object using context
      String name = (String) exp.getValue(context);
      System.out.println(name);

      Employee employee1 = new Employee();
      employee1.setId(2);
      employee1.setName("Rita");

      // evaluate object directly
      name = (String) exp.getValue(employee1);
      System.out.println(name);
      exp = parser.parseExpression("id > 1");
      
      // evaluate object using context
      boolean result = exp.getValue(context, Boolean.class);
      System.out.println(result);  // evaluates to false

      result = exp.getValue(employee1, Boolean.class);
      System.out.println(result);  // evaluates to true
   }
}

Output

Once you are done creating the source and bean configuration files, let us run the application. If everything is fine with your application, it will print the following message −

Mahesh
Rita
false
true

Spring SpEL - XML Based Configuration

SpEL expression can be used in XML based beans configuration

Syntax

Following is an example of using an expression in xml configuration.

<bean id="randomNumberGenerator" class="com.tutorialspoint.RandomNumberGenerator">
   <property name="randomNumber" value="#{ T(java.lang.Math).random() * 100.0 }"/>
</bean> 

Here we have specified a property to be filled in using Math.random() method. In case of classes, its name should be fully qualified. We can use system variables as well using systemProperties. It is a built-in variable.

<property name="country" value="#{ systemProperties['user.country'] }"/>

We can use another bean as well with a SpEL expression as shown below:

<property name="id" value="#{ randomNumberGenerator.randomNumber }"/>

Following example shows the various use cases.

Example - Usage of SpEL in XML based configuration

Let's update the project created in Spring SpEL - Create Project chapter. We're adding/updating following files −

  • RandomNumberGenerator.java − A random number generator class.

  • Employee.java − An employee class.

  • MainApp.java − Main application to run and test.

  • applicationcontext.xml − beans configuration file.

RandomNumberGenerator.java

Here is the content of RandomNumberGenerator.java file −

package com.tutorialspoint;

public class RandomNumberGenerator {
   private int randomNumber;
   public int getRandomNumber() {
      return randomNumber;
   } 
   public void setRandomNumber(int randomNumber) {
      this.randomNumber = randomNumber;
   }
}

Employee.java

Here is the content of Employee.java file −

package com.tutorialspoint;

public class Employee {
   private int id;
   private String name;	
   private String country;
   
   public int getId() {
      return id;
   }
   public void setId(int id) {
      this.id = id;
   }
   public String getName() {
      return name;
   }
   public void setName(String name) {
      this.name = name;
   }
   public String getCountry() {
      return country;
   }
   public void setCountry(String country) {
      this.country = country;
   }
   @Override
   public String toString() {
      return "[" + id + ", " + name + ", " + country + "]";
   }
}

MainApp.java

Here is the content of MainApp.java file −

package com.tutorialspoint;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MainApp {
   public static void main(String[] args) {
      ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationcontext.xml");
      Employee employee = (Employee) applicationContext.getBean("employee");
      System.out.println(employee);
   }
}

applicationcontext.xml

Here is the content of applicationcontext.xml file −

<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans"  
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
   xsi:schemaLocation="http://www.springframework.org/schema/beans   
   http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> 

   <bean id="randomNumberGenerator" class="com.tutorialspoint.RandomNumberGenerator">
      <property name="randomNumber" value="#{ T(java.lang.Math).random() * 100.0 }"/>
   </bean> 
   <bean id="employee" class="com.tutorialspoint.Employee">
      <property name="id" value="#{ randomNumberGenerator.randomNumber }"/>
      <property name="country" value="#{ systemProperties['user.country'] }"/>
      <property name="name" value="Mahesh"/>
   </bean> 
</beans> 

Output

Once you are done creating the source and bean configuration files, let us run the application. If everything is fine with your application, it will print the following message −

[52, Mahesh, IN]

Spring SpEL - Annotation Based Configuration

SpEL expression can be used in Annotation based beans configuration

Syntax

Following is an example of using an expression in annotation based configuration.

@Value("#{ T(java.lang.Math).random() * 100.0 }")
private int id;

Here we are using @Value annotation and we've specified a SpEL expression on a property. Similarly we can specify SpEL expression on setter methods, on constructors and during autowiring as well.

@Value("#{ systemProperties['user.country'] }")
public void setCountry(String country) {
   this.country = country;
}

Following example shows the various use cases.

Example - Usage of SpEL in Annotation based configuration

Let's update the project created in Spring SpEL - Create Project chapter. We're adding/updating following files −

  • Employee.java − An employee class.

  • AppConfig.java − A configuration class.

  • MainApp.java − Main application to run and test.

Employee.java

Here is the content of Employee.java file −

package com.tutorialspoint;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class Employee {
   @Value("#{ T(java.lang.Math).random() * 100.0 }")
   private int id;
   private String name;	
   private String country;

   public int getId() {
      return id;
   }
   public void setId(int id) {
      this.id = id;
   }
   public String getName() {
      return name;
   }
   @Value("Mahesh")
   public void setName(String name) {
      this.name = name;
   }
   public String getCountry() {
      return country;
   }
   @Value("#{ systemProperties['user.country'] }")
   public void setCountry(String country) {
      this.country = country;
   }
   @Override
   public String toString() {
      return "[" + id + ", " + name + ", " + country + "]";
   }
}

AppConfig.java

Here is the content of MainApp.java file −

package com.tutorialspoint;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@ComponentScan(basePackages = "com.tutorialspoint")
public class AppConfig {
}

MainApp.java

Here is the content of MainApp.java file −

package com.tutorialspoint;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class MainApp {
   public static void main(String[] args) {
      AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
      context.register(AppConfig.class);
      context.refresh();

      Employee emp = context.getBean(Employee.class);
      System.out.println(emp);	   
   }
}

Output

Once you are done creating the source and bean configuration files, let us run the application. If everything is fine with your application, it will print the following message −

[50, Mahesh, IN]

Spring SpEL - Literal Expression

SpEL expression supports following types of literals −

  • Strings − Single quote delimited strings. To use single quote, put another single quote around it.

  • Numeric − int, real and hex expressions are supported.

  • boolean

  • null

Following example shows the various use cases.

Example - Usage of literals in SpEL

Let's update the project created in Spring SpEL - Create Project chapter. We're updating following file −

  • MainApp.java − Main application to run and test.

MainApp.java

Here is the content of MainApp.java file −

package com.tutorialspoint;

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 simple text
      String message = (String) parser.parseExpression("'Tutorialspoint'").getValue();
      System.out.println(message);

      // parse a double from exponential expression
      double avogadros  = (Double) parser.parseExpression("6.0221415E+23").getValue();
      System.out.println(avogadros);	

      // parse an int value from Hexadecimal expression
      int intValue = (Integer) parser.parseExpression("0x7FFFFFFF").getValue();
      System.out.println(intValue);

      // parse a boolean 
      boolean booleanValue = (Boolean) parser.parseExpression("true").getValue();
      System.out.println(booleanValue);

      // parse a null object
      Object nullValue = parser.parseExpression("null").getValue();
      System.out.println(nullValue);
   }
}

Output

Once you are done creating the source and bean configuration files, let us run the application. If everything is fine with your application, it will print the following message −

Tutorialspoint
6.0221415E23
2147483647
true
null

Spring SpEL - Properties

SpEL expression supports accessing properties of an object.

  • We can access nested properties as well within an SpEL expression.

  • First letter of a property is case insensitive within an SpEL expression.

Following example shows the various use cases.

Example - Usage of object properties in SpEL

Let's update the project created in Spring SpEL - Create Project chapter. We're adding/updating following files −

  • Employee.java − Employee Class.

  • MainApp.java − Main application to run and test.

Employee.java

Here is the content of Employee.java file −

package com.tutorialspoint;

import java.util.Date;

public class Employee {
   private int id;
   private String name;	
   private Date dateOfBirth;

   public int getId() {
      return id;
   }
   public void setId(int id) {
      this.id = id;
   }
   public String getName() {
      return name;
   }
   public void setName(String name) {
      this.name = name;
   }
   public Date getDateOfBirth() {
      return dateOfBirth;
   }
   public void setDateOfBirth(Date dateOfBirth) {
      this.dateOfBirth = dateOfBirth;
   }
   @Override
   public String toString() {
      return "[" + id + ", " + name + ", " + dateOfBirth + "]";
   }
}

MainApp.java

Here is the content of MainApp.java file −

package com.tutorialspoint;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;

public class MainApp {
   public static void main(String[] args) throws ParseException {
      ExpressionParser parser = new SpelExpressionParser();
      Employee employee = new Employee();
      
      employee.setId(1);
      employee.setName("Mahesh");
      employee.setDateOfBirth(new SimpleDateFormat("YYYY-MM-DD").parse("1985-12-01"));

      EvaluationContext context = new StandardEvaluationContext(employee);
      
      int birthYear = (Integer) parser.parseExpression("dateOfBirth.Year + 1900").getValue(context);	
      System.out.println(birthYear);

      String name = (String) parser.parseExpression("name").getValue(context);	
      System.out.println(name);
   }
}

Output

Once you are done creating the source and bean configuration files, let us run the application. If everything is fine with your application, it will print the following message −

1984
Mahesh

Spring SpEL - Arrays

SpEL expression supports accessing arrays and using their indexes of an array of an object.

  • We can access nested arrays as well within an SpEL expression.

Following example shows the various use cases.

Example - Usage of arrays in SpEL

Let's update the project created in Spring SpEL - Create Project chapter. We're adding/updating following files −

  • Employee.java − Employee class.

  • Dept.java − Department class.

  • MainApp.java − Main application to run and test.

Employee.java

Here is the content of Employee.java file −

package com.tutorialspoint;

public class Employee {
   private String[] awards;
   public String[] getAwards() {
      return awards;
   }
   public void setAwards(String[] awards) {
      this.awards = awards;
   }
}

Dept.java

Here is the content of Dept.java file −

package com.tutorialspoint;

public class Dept {
   private Employee[] employees;
   public Employee[] getEmployees() {
      return employees;
   }
   public void setEmployees(Employee[] employees) {
      this.employees = employees;
   }
}

MainApp.java

Here is the content of MainApp.java file −

package com.tutorialspoint;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;

public class MainApp {
   public static void main(String[] args) throws ParseException {
      ExpressionParser parser = new SpelExpressionParser();
      Employee employee = new Employee();
      String[] awards = {"Star of the Month", "Champion", "Accelerator"};
      employee.setAwards(awards);

      Employee[] employees = { employee };
      Dept dept = new Dept();
      dept.setEmployees(employees);
      EvaluationContext employeeContext = new StandardEvaluationContext(employee);

      // evaluates to "Accelerator"
      String award = parser.parseExpression("awards[2]").getValue(employeeContext, String.class);
      System.out.println(award);
      EvaluationContext deptContext = new StandardEvaluationContext(dept);

      // evaluates to "Champion"
      award = parser.parseExpression("employees[0].awards[1]").getValue(deptContext, String.class);
      System.out.println(award);
   }
}

Output

Once you are done creating the source and bean configuration files, let us run the application. If everything is fine with your application, it will print the following message −

Accelerator
Champion

Spring SpEL - List

SpEL expression supports accessing list and using their indexes of an list of an object.

  • We can access nested lists as well within an SpEL expression.

Following example shows the various use cases.

Example - Usage of lists in SpEL

Let's update the project created in Spring SpEL - Create Project chapter. We're adding/updating following files −

  • Employee.java − Employee class.

  • Dept.java − Department class.

  • MainApp.java − Main application to run and test.

Employee.java

Here is the content of Employee.java file −

package com.tutorialspoint;

import java.util.List;

public class Employee {
   private List<String> awards;
   public List<String> getAwards() {
      return awards;
   }
   public void setAwards(List<String> awards) {
      this.awards = awards;
   }
}

Dept.java

Here is the content of Dept.java file −

package com.tutorialspoint;

import java.util.List;

public class Dept {
   private List<Employee> employees;
   public List<Employee> getEmployees() {
      return employees;
   }
   public void setEmployees(List<Employee> employees) {
      this.employees = employees;
   }
}

MainApp.java

Here is the content of MainApp.java file −

package com.tutorialspoint;

import java.text.ParseException;
import java.util.Arrays;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;

public class MainApp {
   public static void main(String[] args) throws ParseException {
      ExpressionParser parser = new SpelExpressionParser();
      Employee employee = new Employee();
      employee.setAwards(Arrays.asList("Star of the Month", "Champion", "Accelerator"));

      Dept dept = new Dept();
      dept.setEmployees(Arrays.asList(employee));
      EvaluationContext employeeContext = new StandardEvaluationContext(employee);

      // evaluates to "Accelerator"
      String award = parser.parseExpression("awards.get(2)").getValue(employeeContext, String.class);
      System.out.println(award);

      EvaluationContext deptContext = new StandardEvaluationContext(dept);

      // evaluates to "Champion"
      award = parser.parseExpression("employees.get(0).awards.get(1)").getValue(deptContext, String.class);
      System.out.println(award);
   }
}

Output

Once you are done creating the source and bean configuration files, let us run the application. If everything is fine with your application, it will print the following message −

Accelerator
Champion

Spring SpEL - Map

SpEL expression supports accessing map.

Following example shows the various use cases.

Example - Usage of Maps in SpEL

Let's update the project created in Spring SpEL - Create Project chapter. We're adding/updating following files −

  • Employee.java − Employee class.

  • MainApp.java − Main application to run and test.

Employee.java

Here is the content of Employee.java file −

package com.tutorialspoint;

import java.util.Map;

public class Employee {
   private Map<String, String> offices;
   public Map<String, String> getOffices() {
      return offices;
   }
   public void setOffices(Map<String, String> offices) {
      this.offices = offices;
   }
}

MainApp.java

Here is the content of MainApp.java file −

package com.tutorialspoint;

import java.text.ParseException;
import java.util.HashMap;
import java.util.Map;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;

public class MainApp {
   public static void main(String[] args) throws ParseException {
      ExpressionParser parser = new SpelExpressionParser();
      Employee employee = new Employee();
      Map<String, String> officeMap = new HashMap();
      officeMap.put("IN", "Hyderabad");
      officeMap.put("UK", "London");

      employee.setOffices(officeMap);
      EvaluationContext employeeContext = new StandardEvaluationContext(employee);

      // evaluates to "Hyderabad"
      String city = parser.parseExpression("offices['IN']").getValue(employeeContext, String.class);
      System.out.println(city);
   }
}

Output

Once you are done creating the source and bean configuration files, let us run the application. If everything is fine with your application, it will print the following message −

Hyderabad

Spring SpEL - Methods

SpEL expression supports accessing methods of an object.

Following example shows the various use cases.

Example - Usage of Maps in SpEL

Let's update the project created in Spring SpEL - Create Project chapter. We're adding/updating following files −

  • Employee.java − Employee class.

  • MainApp.java − Main application to run and test.

Employee.java

Here is the content of Employee.java file −

package com.tutorialspoint;

import java.util.List;

public class Employee {
   private List<String> awards;
   public List<String> getAwards() {
      return awards;
   }
   public void setAwards(List<String> awards) {
      this.awards = awards;
   }
   public boolean isAwardee() {
      return awards != null && awards.size() > 0;
   }
}

MainApp.java

Here is the content of MainApp.java file −

package com.tutorialspoint;

import java.text.ParseException;
import java.util.Arrays;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;

public class MainApp {
   public static void main(String[] args) throws ParseException {
      ExpressionParser parser = new SpelExpressionParser();
      Employee employee = new Employee();
      employee.setAwards(Arrays.asList("Star of the Month", "Champion", "Accelerator"));
      EvaluationContext employeeContext = new StandardEvaluationContext(employee);

      // string literal, evaluates to "t"
      String t = parser.parseExpression("'Tutorials'.substring(2, 3)").getValue(String.class);
      System.out.println(t);

      // evaluates to true
      boolean isAwardee = parser.parseExpression("isAwardee()").getValue(employeeContext, Boolean.class);
      System.out.println(isAwardee);
   }
}

Output

Once you are done creating the source and bean configuration files, let us run the application. If everything is fine with your application, it will print the following message −

t
true

Spring SpEL - Relational Operators

SpEL expression supports relational operators like <, >, equals etc. It also support instance of and matches operators.

Following example shows the various use cases.

Example - Usage of Relational Operators in SpEL

Let's update the project created in Spring SpEL - Create Project chapter. We're updating following file −

  • MainApp.java − Main application to run and test.

MainApp.java

Here is the content of MainApp.java file −

package com.tutorialspoint;

import java.text.ParseException;

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

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

      // evaluates to true
      boolean result = parser.parseExpression("2 == 2").getValue(Boolean.class);
      System.out.println(result);

      // evaluates to false
      result = parser.parseExpression("2 < -5.0").getValue(Boolean.class);
      System.out.println(result);

      // evaluates to true
      result = parser.parseExpression("'black' < 'block'").getValue(Boolean.class);
      System.out.println(result);

      // evaluates to false
      result = parser.parseExpression("'xyz' instanceof T(int)").getValue(Boolean.class);
      System.out.println(result);

      // evaluates to false
      result = parser.parseExpression("'5.0067' matches '^-?\\d+(\\.\\d{2})?$'").getValue(Boolean.class);
      System.out.println(result);
   }
}

Output

Once you are done creating the source and bean configuration files, let us run the application. If everything is fine with your application, it will print the following message −

true
false
true
false
false

Spring SpEL - Logical Operators

SpEL expression supports logical operators like AND, OR and NOT.

Following example shows the various use cases.

Example - Usage of Logical Operators in SpEL

Let's update the project created in Spring SpEL - Create Project chapter. We're updating following file −

  • MainApp.java − Main application to run and test.

MainApp.java

Here is the content of MainApp.java file −

package com.tutorialspoint;

import java.text.ParseException;

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

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

      // evaluates to true
      boolean result = parser.parseExpression("true and true").getValue(Boolean.class);
      System.out.println(result);

      // evaluates to true
      result = parser.parseExpression("true or false").getValue(Boolean.class);
      System.out.println(result);

      // evaluates to false
      result = parser.parseExpression("!true").getValue(Boolean.class);
      System.out.println(result);
   }
}

Output

Once you are done creating the source and bean configuration files, let us run the application. If everything is fine with your application, it will print the following message −

true
true
false

Spring SpEL - Mathematical Operators

SpEL expression supports mathematical operators like +, -, * etc.

Following example shows the various use cases.

Example - Usage of Mathematical Operators in SpEL

Let's update the project created in Spring SpEL - Create Project chapter. We're updating following file −

  • MainApp.java − Main application to run and test.

MainApp.java

Here is the content of MainApp.java file −

package com.tutorialspoint;

import java.text.ParseException;

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

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

      // evaluates to 5
      int result = parser.parseExpression("3 + 2").getValue(Integer.class);
      System.out.println(result);

      // evaluates to 1
      result = parser.parseExpression("3 - 2").getValue(Integer.class);
      System.out.println(result);

      // evaluates to 6
      result = parser.parseExpression("3 * 2").getValue(Integer.class);
      System.out.println(result);

      // evaluates to 1
      result = parser.parseExpression("3 / 2").getValue(Integer.class);
      System.out.println(result);

      // evaluates to 1
      result = parser.parseExpression("3 % 2").getValue(Integer.class);
      System.out.println(result);

      // follow operator precedence, evaluate to -9
      result = parser.parseExpression("1+2-3*4").getValue(Integer.class); 
      System.out.println(result);
   }
}

Output

Once you are done creating the source and bean configuration files, let us run the application. If everything is fine with your application, it will print the following message −

5
1
6
1
1
-9

Spring SpEL - Assignment Operator

SpEL expression supports assignment of properties using setValue() method as well as using assignment operator.

Following example shows the various use cases.

Example - Usage of Assignment Operator in SpEL

Let's update the project created in Spring SpEL - Create Project chapter. We're updating following files −

  • Employee.java − Employee class.

  • MainApp.java − Main application to run and test.

Employee.java

Here is the content of Employee.java file −

package com.tutorialspoint;

public class Employee {
   private String name;
   public String getName() {
      return name;
   }
   public void setName(String name) {
      this.name = name;
   }
}

MainApp.java

Here is the content of MainApp.java file −

package com.tutorialspoint;

import java.text.ParseException;

import org.springframework.expression.EvaluationContext;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;

public class MainApp {
   public static void main(String[] args) throws ParseException {
      ExpressionParser parser = new SpelExpressionParser();
      Employee employee = new Employee();   
      EvaluationContext employeeContext = new StandardEvaluationContext(employee);

      // Using setValue
      parser.parseExpression("name").setValue(employeeContext, "Mahesh");
      String result = parser.parseExpression("name").getValue(employeeContext, String.class);
      System.out.println(result);

      // Using assignment operator
      result = parser.parseExpression("Name = 'Robert'").getValue(employeeContext, String.class);
      System.out.println(result);
   }
}

Output

Once you are done creating the source and bean configuration files, let us run the application. If everything is fine with your application, it will print the following message −

Mahesh
Robert

Spring SpEL - Ternary Operator

SpEL expression supports ternary operator to perform if-then-else logic.

Following example shows the various use cases.

Example - Usage of Ternary Operator in SpEL

Let's update the project created in Spring SpEL - Create Project chapter. We're updating following file −

  • MainApp.java − Main application to run and test.

MainApp.java

Here is the content of MainApp.java file −

package com.tutorialspoint;

import java.text.ParseException;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;

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

      String result = parser.parseExpression("true ? 'Yes' : 'No'").getValue(String.class);
      System.out.println(result);

      result = parser.parseExpression("false ? 'Yes' : 'No'").getValue(String.class);
      System.out.println(result);
   }
}

Output

Once you are done creating the source and bean configuration files, let us run the application. If everything is fine with your application, it will print the following message −

Yes
No

Spring SpEL - Elvis Operator

SpEL expression supports Elvis operator which is a short form of ternary operator.

// Using ternary operator
String result = name != null ? name: "unknown";

// Using Elvis Operator
result = name?:"unknown";

Following example shows the various use cases.

Example - Usage of Elvis Operator in SpEL

Let's update the project created in Spring SpEL - Create Project chapter. We're updating following files −

  • Employee.java − Employee Class.

  • MainApp.java − Main application to run and test.

Employee.java

Here is the content of Employee.java file −

package com.tutorialspoint;

public class Employee {
   private String name;

   public String getName() {
      return name;
   }
   public void setName(String name) {
      this.name = name;
   }
}

MainApp.java

Here is the content of MainApp.java file −

package com.tutorialspoint;

import java.text.ParseException;

import org.springframework.expression.EvaluationContext;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;

public class MainApp {
   public static void main(String[] args) throws ParseException {
      ExpressionParser parser = new SpelExpressionParser();
      Employee employee = new Employee();   
      EvaluationContext employeeContext = new StandardEvaluationContext(employee);

      // Evaluates to "unknown"
      String result = parser.parseExpression("name?:'unknown'").getValue(employeeContext, String.class);
      System.out.println(result);

      employee.setName("Mahesh");

      // Evaluates to "Mahesh"
      result = parser.parseExpression("name?:'unknown'").getValue(employeeContext, String.class);
      System.out.println(result);
   }
}

Output

Once you are done creating the source and bean configuration files, let us run the application. If everything is fine with your application, it will print the following message −

unknown
Mahesh

Spring SpEL - Safe Navigation Operator

SpEL expression supports Safe Navigation operator which is used to avoid NullPointerException.

int length = parser.parseExpression("name?.length").getValue(context, Integer.class);

Here if name is null, then expression will not throw null pointer exception.

Following example shows the various use cases.

Example - Usage of Safe Navigation Operator in SpEL

Let's update the project created in Spring SpEL - Create Project chapter. We're updating following files −

  • Employee.java − Employee Class.

  • MainApp.java − Main application to run and test.

Employee.java

Here is the content of Employee.java file −

package com.tutorialspoint;

public class Employee {
   private String name;

   public String getName() {
      return name;
   }
   public void setName(String name) {
      this.name = name;
   }
}

MainApp.java

Here is the content of MainApp.java file −

package com.tutorialspoint;

import java.text.ParseException;

import org.springframework.expression.EvaluationContext;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;

public class MainApp {
   public static void main(String[] args) throws ParseException {
      ExpressionParser parser = new SpelExpressionParser();
      Employee employee = new Employee();   
      EvaluationContext employeeContext = new StandardEvaluationContext(employee);

      // Evaluates to null but will not throw null pointer exception during parseExpression
      String result = parser.parseExpression("name?.strip()").getValue(employeeContext, String.class);
      System.out.println(result);
      employee.setName("   Mahesh   ");

      // Evaluates to "Mahesh"
      result = parser.parseExpression("name?.strip()").getValue(employeeContext, String.class);
      System.out.println(result);	   
   }
}

Output

Once you are done creating the source and bean configuration files, let us run the application. If everything is fine with your application, it will print the following message −

null
Mahesh

Spring SpEL - Collection Selection

SpEL expression supports Collection Selection which is a very powerful expression allowing to transform source collection into another by selecting the entries from the source collection.

Syntax

?[selectionExpresion]

Following example shows the usage.

List<Employee> list = (List<Employee>)
   parser.parseExpression("employees.?[country == 'USA']").getValue(deptContext);

Here SpEL will return only those employees from the list of employees whose country is USA.

Following example shows the various use cases.

Example - Usage of Selection in Collection in SpEL

Let's update the project created in Spring SpEL - Create Project chapter. We're updating following files −

  • Employee.java − Employee Class.

  • Dept.java − Department Class.

  • MainApp.java − Main application to run and test.

Employee.java

Here is the content of Employee.java file −

package com.tutorialspoint;

public class Employee {
   private String name;
   private String country;

   public Employee(String name, String country) {
      this.name = name;
      this.country = country;
   }
   public String getName() {
      return name;
   }
   public void setName(String name) {
      this.name = name;
   }
   public String getCountry() {
      return country;
   }
   public void setCountry(String country) {
      this.country = country;
   }
   public String toString() {
      return "[" +name+ ", "+country + "]";
   }
}

Dept.java

Here is the content of Dept.java file −

package com.tutorialspoint;

import java.util.List;

public class Dept {
   private List<Employee> employees;
   public List<Employee> getEmployees() {
      return employees;
   }
   public void setEmployees(List<Employee> employees) {
      this.employees = employees;
   }
}

MainApp.java

Here is the content of MainApp.java file −

package com.tutorialspoint;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;

import org.springframework.expression.EvaluationContext;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;

public class MainApp {
   public static void main(String[] args) throws ParseException {
      ExpressionParser parser = new SpelExpressionParser();
      Employee employee1 = new Employee("Robert", "USA");
      Employee employee2 = new Employee("Julie", "USA");
      Employee employee3 = new Employee("Ramesh", "India");

      List<Employee> employees = new ArrayList<Employee>();
      employees.add(employee1);
      employees.add(employee2);
      employees.add(employee3);

      Dept dept = new Dept();
      dept.setEmployees(employees);
      EvaluationContext deptContext = new StandardEvaluationContext(dept);

      // Select list of employees who are living in USA
      List<Employee> list = (List<Employee>)
         parser.parseExpression("employees.?[country == 'USA']").getValue(deptContext);
      System.out.println(list);
   }
}

Output

Once you are done creating the source and bean configuration files, let us run the application. If everything is fine with your application, it will print the following message −

[[Robert, USA], [Julie, USA]]

Spring SpEL - Collection Projection

SpEL expression supports Collection Projection which is a very powerful expression allowing to evaluate sub-expression and in result returns a new collection.

Syntax

![projectionExpresion]

Following example shows the usage.

List<String> list = (List<String>)
   parser.parseExpression("employees.![country]").getValue(deptContext);

Here SpEL will return the countries as a list of strings from the list of employees.

Following example shows the various use cases.

Example - Usage of Projection in Collection in SpEL

Let's update the project created in Spring SpEL - Create Project chapter. We're updating following files −

  • Employee.java − Employee Class.

  • Dept.java − Department Class.

  • MainApp.java − Main application to run and test.

Employee.java

Here is the content of Employee.java file −

package com.tutorialspoint;

public class Employee {
   private String name;
   private String country;

   public Employee(String name, String country) {
      this.name = name;
      this.country = country;
   }
   public String getName() {
      return name;
   }
   public void setName(String name) {
      this.name = name;
   }
   public String getCountry() {
      return country;
   }
   public void setCountry(String country) {
      this.country = country;
   }
   public String toString() {
      return "[" +name+ ", "+country + "]";
   }
}

Dept.java

Here is the content of Dept.java file −

package com.tutorialspoint;

import java.util.List;

public class Dept {
   private List<Employee> employees;
   public List<Employee> getEmployees() {
      return employees;
   }
   public void setEmployees(List<Employee> employees) {
      this.employees = employees;
   }
}

MainApp.java

Here is the content of MainApp.java file −

package com.tutorialspoint;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;

import org.springframework.expression.EvaluationContext;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;

public class MainApp {
   public static void main(String[] args) throws ParseException {

      ExpressionParser parser = new SpelExpressionParser();

      Employee employee1 = new Employee("Robert", "USA");
      Employee employee2 = new Employee("Julie", "USA");
      Employee employee3 = new Employee("Ramesh", "India");

      List<Employee> employees = new ArrayList<Employee>();
      employees.add(employee1);
      employees.add(employee2);
      employees.add(employee3);

      Dept dept = new Dept();
      dept.setEmployees(employees);

      EvaluationContext deptContext = new StandardEvaluationContext(dept);

      // Select list of countries
      List<String> list = (List<String>)
         parser.parseExpression("employees.![country]").getValue(deptContext);
      System.out.println(list);
   }
}

Output

Once you are done creating the source and bean configuration files, let us run the application. If everything is fine with your application, it will print the following message −

[USA, USA, India]

Spring SpEL - Constructor

SpEL expression supports creating objects within expressions using new operator. We need to pass the fully qualified name of the class.

Syntax

![projectionExpresion]

Following example shows the usage.

Employee robert = 
   parser.parseExpression("new com.tutorialspoint.Employee('Robert','USA')").getValue(Employee.class);

Here SpEL will return the employee object.

Following example shows the various use cases.

Example - Usage of Projection in Collection in SpEL

Let's update the project created in Spring SpEL - Create Project chapter. We're updating following files −

  • Employee.java − Employee Class.

  • Dept.java − Department Class.

  • MainApp.java − Main application to run and test.

Employee.java

Here is the content of Employee.java file −

package com.tutorialspoint;

public class Employee {
   private String name;
   private String country;

   public Employee(String name, String country) {
      this.name = name;
      this.country = country;
   }
   public String getName() {
      return name;
   }
   public void setName(String name) {
      this.name = name;
   }
   public String getCountry() {
      return country;
   }
   public void setCountry(String country) {
      this.country = country;
   }
   public String toString() {
      return "[" +name+ ", "+country + "]";
   }
}

Dept.java

Here is the content of Dept.java file −

package com.tutorialspoint;

import java.util.List;

public class Dept {
   private List<Employee> employees;
   public List<Employee> getEmployees() {
      return employees;
   }
   public void setEmployees(List<Employee> employees) {
      this.employees = employees;
   }
}

MainApp.java

Here is the content of MainApp.java file −

package com.tutorialspoint;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;

import org.springframework.expression.EvaluationContext;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;

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

      List<Employee> employees = new ArrayList<Employee>();	   
      Employee robert = parser.parseExpression("new com.tutorialspoint.Employee('Robert','USA')")
         .getValue(Employee.class);
      employees.add(robert);

      Dept dept = new Dept();
      dept.setEmployees(employees);
      System.out.println(employees);

      EvaluationContext deptContext = new StandardEvaluationContext(dept);
      parser.parseExpression("employees.add(new com.tutorialspoint.Employee('Julie','USA'))")
         .getValue(deptContext);
      System.out.println(employees);
   }
}

Output

Once you are done creating the source and bean configuration files, let us run the application. If everything is fine with your application, it will print the following message −

[[Robert, USA]]
[[Robert, USA], [Julie, USA]]

Spring SpEL - Variables

SpEL expression allows to create and use variables specific to expression using #variable-name syntax. A variable is set using setVariable on EvaluationContext. There are two types of inbuilt variables as well, #this and #root. #this variable always refers to current evaluation object where as #root variable refers to the root object of the evaluation context.

Syntax

context.setVariable("newName", "Mahesh Kumar");

Following example shows the various use cases.

Example - Usage of Projection in Collection in SpEL

Let's update the project created in Spring SpEL - Create Project chapter. We're updating following files −

  • Employee.java − Employee Class.

  • MainApp.java − Main application to run and test.

Employee.java

Here is the content of Employee.java file −

package com.tutorialspoint;

public class Employee {
   private String name;
   private String country;

   public Employee(String name, String country) {
      this.name = name;
      this.country = country;
   }
   public String getName() {
      return name;
   }
   public void setName(String name) {
      this.name = name;
   }
   public String getCountry() {
      return country;
   }
   public void setCountry(String country) {
      this.country = country;
   }
   public String toString() {
      return "[" +name+ ", "+country + "]";
   }
}

MainApp.java

Here is the content of MainApp.java file −

package com.tutorialspoint;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.springframework.expression.EvaluationContext;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;

public class MainApp {
   public static void main(String[] args) throws ParseException {
      ExpressionParser parser = new SpelExpressionParser();
      Employee employee = new Employee("Mahesh", "INDIA");

      EvaluationContext context = new StandardEvaluationContext(employee);
      context.setVariable("newName", "Mahesh Parashar");
      parser.parseExpression("Name = #newName").getValue(context);

      // Evaluate to "Mahesh Parashar"
      System.out.println(employee.getName());
      List<Integer> primes = new ArrayList<Integer>();
      primes.addAll(Arrays.asList(2,3,5,7,11,13,17));

      context.setVariable("primes",primes);

      List<Integer> filteredList =
      (List<Integer>) parser.parseExpression("#primes.?[#this>10]").getValue(context);

      // Evaluate to [11, 13, 17], prime numbers greater than 10
      System.out.println(filteredList);
   }
}

Output

Once you are done creating the source and bean configuration files, let us run the application. If everything is fine with your application, it will print the following message −

Mahesh Parashar
[11, 13, 17]

Spring SpEL - Functions

SpEL expression allows to create and use functions specific to expression using #function-name syntax. A function is set using registerFunction on EvaluationContext.

Syntax

context.registerFunction("reverse", 
   MainApp.class.getDeclaredMethod("reverse", new Class[] { String.class }));

Following example shows the various use cases.

Example - Usage of Projection in Collection in SpEL

Let's update the project created in Spring SpEL - Create Project chapter. We're updating following file −

  • MainApp.java − Main application to run and test.

MainApp.java

Here is the content of MainApp.java file −

package com.tutorialspoint;

import java.text.ParseException;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;

public class MainApp {
   public static void main(String[] args) throws ParseException, NoSuchMethodException, SecurityException {
      ExpressionParser parser = new SpelExpressionParser();
      StandardEvaluationContext context = new StandardEvaluationContext();

      context.registerFunction("reverse",
      MainApp.class.getDeclaredMethod("reverse", new Class[] { String.class }));

      String reverseString=parser.parseExpression("#reverse('main')").getValue(context, String.class);
      System.out.println(reverseString);
   }
   public static String reverse(String input) {
      StringBuilder backwards = new StringBuilder();
      for (int i = 0; i < input.length(); i++) {
         backwards.append(input.charAt(input.length() - 1 - i));
      }
      return backwards.toString();
   }
}

Output

Once you are done creating the source and bean configuration files, let us run the application. If everything is fine with your application, it will print the following message −

niam

Spring SpEL - Expression Templating

SpEL expression allows to mix literal text with evaluation block(s). Each evaluation block is to be prefixed and suffixed properly. Standard choice is to use #{}. org.springframework.expression.common. TemplateParserContext uses the #{}

Syntax

String result = parser.parseExpression("Random number : #{T(java.lang.Math).random() * 100}", 
   new TemplateParserContext()).getValue(String.class);

Following example shows the various use cases.

Example - Usage of Projection in Collection in SpEL

Let's update the project created in Spring SpEL - Create Project chapter. We're updating following file −

  • MainApp.java − Main application to run and test.

MainApp.java

Here is the content of MainApp.java file −

package com.tutorialspoint;

import java.text.ParseException;

import org.springframework.expression.ExpressionParser;
import org.springframework.expression.common.TemplateParserContext;
import org.springframework.expression.spel.standard.SpelExpressionParser;

public class MainApp {
   public static void main(String[] args) throws ParseException, NoSuchMethodException, SecurityException {
      ExpressionParser parser = new SpelExpressionParser();
      String result=parser.parseExpression("Random number : #{T(java.lang.Math).random() * 100}", 
         new TemplateParserContext()).getValue(String.class);
      System.out.println(result);
   }
}

Output

Once you are done creating the source and bean configuration files, let us run the application. If everything is fine with your application, it will print the following message −

Random number : 43.15856974355583
Advertisements