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.

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 Framework. It will also teach you how to set up JDK, Maven and Eclipse on your machine before you set up Spring Framework −

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-11.0.11, you would have to put the following line in your C:\autoexec.bat file.

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

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-11.0.11 and you use the C shell, you will have to put the following into your .cshrc file.

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

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.

Setup Eclipse IDE

All the examples in this tutorial have been written using Eclipse IDE. So we would suggest you should have the latest version of Eclipse installed on your machine.

To install Eclipse IDE, download the latest Eclipse binaries from www.eclipse.org/downloads. Once you download the installation, unpack the binary distribution into a convenient location. For example, in C:\eclipse on Windows, or /usr/local/eclipse on Linux/Unix and finally set PATH variable appropriately.

Eclipse can be started by executing the following commands on Windows machine, or you can simply double-click on eclipse.exe

%C:\eclipse\eclipse.exe 

Eclipse can be started by executing the following commands on Unix (Solaris, Linux, etc.) machine −

$/usr/local/eclipse/eclipse

After a successful startup, if everything is fine then it should display the following result −

Eclipse Home page

Set Maven

In this tutorial, we are using maven to run and build the spring based examples. Follow the Maven - Environment Setup to install maven.

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

Spring SpEL - Create 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 − springspel

  • 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>
      <org.springframework.version>5.3.9</org.springframework.version>
      <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
      <java.version>1.8</java.version>    
   </properties> 
   <dependencies>
      <dependency>
         <groupId>org.springframework</groupId>
         <artifactId>spring-context</artifactId>
         <version>${org.springframework.version}</version>
         <scope>compile</scope>
      </dependency>
   </dependencies>	    
   <build>
      <plugins>
         <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.1</version>
            <configuration>
               <source>${java.version}</source>
               <target>${java.version}</target>
            </configuration>
         </plugin>
      </plugins>
   </build>
</project>

applicationcontext.xml

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

applicationcontext.xml

<?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 - Expression 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
  • 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

Spring SpEL - EvaluationContext

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

The following example shows a class MainApp.

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

  • Employee.java − Employee class.

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

Here is the content of Employee.java file −

package com.tutorialspoint;

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

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

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

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.

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;
   }
}

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 + "]";
   }
}

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

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

[84, 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

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.

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 + "]";
   }
}

Here is the content of AppConfig.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 {
}

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

[84, 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

Let's update the project created in Spring SpEL - Create Project chapter. We're adding/updating 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.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

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

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.

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 + "]";
   }
}

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

1984
Mahesh

Spring SpEL - Array

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

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.

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;
   }
}

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;
   }
}

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

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

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.

Here is the content of Employee.java file −

package com.tutorialspoint;

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

Here is the content of Dept.java file −

package com.tutorialspoint;

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

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

Accelerator
Champion

Spring SpEL - Map

SpEL expression supports accessing map.

Following example shows the various use cases.

Example

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.

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;
   }
}

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

Hyderabad

Spring SpEL - Methods

SpEL expression supports accessing methods of an object.

Following example shows the various use cases.

Example

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.

Here is the content of Employee.java file −

package com.tutorialspoint;

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;
   }
}

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

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

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

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

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

      // 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

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

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

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

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

      // 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

true
true
false

Spring SpEL - Mathematical Operators

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

Following example shows the various use cases.

Example

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

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

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

 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

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

  • Employee.java − Employee object.

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

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;
   }
}

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

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

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

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

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

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

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.

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;
   }
}

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

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

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.

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;
   }
}

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

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

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.

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 + "]";
   }
}

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;
   }
}

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

[[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 only those employees from the list of employees whose country is USA.

Following example shows the various use cases.

Example

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.

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 + "]";
   }
}

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;
   }
}

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

[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

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

Following example shows the various use cases.

Example

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.

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 + "]";
   }
}

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;
   }
   public String toString() {
      return "[" + employees.toString() + "]";
   }
}

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

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

Output

[[[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

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.

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 + "]";
   }
}

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

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

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

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

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

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. TemplateParserContextTemplateParserContext uses the same.

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

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

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

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

Random number : 18.056323318070998
Advertisements