English 中文(简体)
Spring SpEL - Quick Guide
  • 时间:2024-11-03

Spring SpEL - Quick Guide


Previous Page Next Page  

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 pke method invocation and basic string templating functionapty.

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 portfopo. While SpEL serves as the foundation for expression evaluation within the Spring portfopo, it is not directly tied to Spring and can be used independently.

Following is the pst of functionapties that Spring Expression Language, SpEL supports:

    Literal expressions

    Boolean and relational operators

    Regular expressions

    Class expressions

    Accessing properties, arrays, psts, maps

    Method invocation

    Relational operators

    Assignment

    Calpng constructors

    Bean references

    Array construction

    Inpne psts

    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 Ecppse 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 instalpng 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 pne 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-cpck on My Computer, select Properties → Advanced → Environment Variables. Then, you will have to update the PATH value and cpck 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) pke Borland JBuilder, Ecppse, IntelpJ 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 Ecppse IDE

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

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

Ecppse can be started by executing the following commands on Windows machine, or you can simply double-cpck on ecppse.exe


%C:ecppseecppse.exe 

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


$/usr/local/ecppse/ecppse

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

Ecppse 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 ecppse, select FileNew Maven Project. Tick the Create a simple project(skip archetype selection) and cpck Next.

Enter the details, as shown below −

    groupId − com.tutorialspoint

    artifactId − springspel

    version − 0.0.1-SNAPSHOT

    name − springspel

    description − Spring SpEL Project

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

apppcationcontext.xml

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

apppcationcontext.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 calpng methods, calpng 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 apppcation 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;

pubpc class MainApp {
   pubpc 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);

      //Calpng 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 apppcation to run and test.

Here is the content of Employee.java file −


package com.tutorialspoint;

pubpc class Employee {
   private String id;
   private String name;
   pubpc String getId() {
      return id;
   }
   pubpc void setId(String id) {
      this.id = id;
   }
   pubpc String getName() {
      return name;
   }
   pubpc 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;

pubpc class MainApp {
   pubpc 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 quapfied. 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 apppcation to run and test.

    apppcationcontext.xml − beans configuration file.

Here is the content of RandomNumberGenerator.java file −


package com.tutorialspoint;
pubpc class RandomNumberGenerator {
   private int randomNumber;
   pubpc int getRandomNumber() {
      return randomNumber;
   } 
   pubpc void setRandomNumber(int randomNumber) {
      this.randomNumber = randomNumber;
   }
}

Here is the content of Employee.java file −


package com.tutorialspoint;

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

Here is the content of MainApp.java file −


package com.tutorialspoint;

import org.springframework.context.ApppcationContext;
import org.springframework.context.support.ClassPathXmlApppcationContext;

pubpc class MainApp {
   pubpc static void main(String[] args) {
      ApppcationContext apppcationContext = new ClassPathXmlApppcationContext("apppcationcontext.xml");
      Employee employee = (Employee) apppcationContext.getBean("employee");
      System.out.println(employee);
   }
}

Here is the content of apppcationcontext.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 ] }")
pubpc 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 apppcation 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
pubpc class Employee {
   @Value("#{ T(java.lang.Math).random() * 100.0 }")
   private int id;
   private String name;	
   private String country;

   pubpc int getId() {
      return id;
   }
   pubpc void setId(int id) {
      this.id = id;
   }
   pubpc String getName() {
      return name;
   }
   @Value("Mahesh")
   pubpc void setName(String name) {
      this.name = name;
   }
   pubpc String getCountry() {
      return country;
   }
   @Value("#{ systemProperties[ user.country ] }")
   pubpc void setCountry(String country) {
      this.country = country;
   }
   @Override
   pubpc 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")
pubpc class AppConfig {
}

Here is the content of MainApp.java file −


package com.tutorialspoint;

import org.springframework.context.annotation.AnnotationConfigApppcationContext;

pubpc class MainApp {
   pubpc static void main(String[] args) {
      AnnotationConfigApppcationContext context = new AnnotationConfigApppcationContext();
      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 pterals −

    Strings − Single quote depmited 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 apppcation 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;

pubpc class MainApp {
   pubpc 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 apppcation to run and test.

Here is the content of Employee.java file −


package com.tutorialspoint;

import java.util.Date;

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

   pubpc int getId() {
      return id;
   }
   pubpc void setId(int id) {
      this.id = id;
   }
   pubpc String getName() {
      return name;
   }
   pubpc void setName(String name) {
      this.name = name;
   }
   pubpc Date getDateOfBirth() {
      return dateOfBirth;
   }
   pubpc void setDateOfBirth(Date dateOfBirth) {
      this.dateOfBirth = dateOfBirth;
   }
   @Override
   pubpc 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;

pubpc class MainApp {
   pubpc 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 apppcation to run and test.

Here is the content of Employee.java file −


package com.tutorialspoint;

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

Here is the content of Dept.java file −


package com.tutorialspoint;

pubpc class Dept {
   private Employee[] employees;
   pubpc Employee[] getEmployees() {
      return employees;
   }
   pubpc 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;

pubpc class MainApp {
   pubpc 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 pst and using their indexes of an pst of an object.

    We can access nested psts 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 apppcation to run and test.

Here is the content of Employee.java file −


package com.tutorialspoint;

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

Here is the content of Dept.java file −


package com.tutorialspoint;

pubpc class Dept {
   private List<Employee> employees;
   pubpc List<Employee> getEmployees() {
      return employees;
   }
   pubpc 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;

pubpc class MainApp {
   pubpc 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 apppcation to run and test.

Here is the content of Employee.java file −


package com.tutorialspoint;

import java.util.Map;

pubpc class Employee {
   private Map<String, String> offices;
   pubpc Map<String, String> getOffices() {
      return offices;
   }
   pubpc 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;

pubpc class MainApp {
   pubpc 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 apppcation to run and test.

Here is the content of Employee.java file −


package com.tutorialspoint;

pubpc class Employee {
   private List<String> awards;
   pubpc List<String> getAwards() {
      return awards;
   }
   pubpc void setAwards(List<String> awards) {
      this.awards = awards;
   }
   pubpc 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;

pubpc class MainApp {
   pubpc 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 pteral, 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 pke <, >, 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 apppcation 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;

pubpc class MainApp {
   pubpc 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 pke 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 apppcation 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;

pubpc class MainApp {
   pubpc 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 pke +, -, * 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 apppcation 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;

pubpc class MainApp {
   pubpc 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 apppcation to run and test.

Here is the content of Employee.java file −


package com.tutorialspoint;

pubpc class Employee {
   private String name;
   pubpc String getName() {
      return name;
   }
   pubpc 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;

pubpc class MainApp {
   pubpc 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 apppcation 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;

pubpc class MainApp {
   pubpc 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 apppcation to run and test.

Here is the content of Employee.java file −


package com.tutorialspoint;

pubpc class Employee {
   private String name;

   pubpc String getName() {
      return name;
   }
   pubpc 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;

pubpc class MainApp {
   pubpc 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 apppcation to run and test.

Here is the content of Employee.java file −


package com.tutorialspoint;

pubpc class Employee {
   private String name;
   pubpc String getName() {
      return name;
   }
   pubpc 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;

pubpc class MainApp {
   pubpc 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> pst = (List<Employee>)
   parser.parseExpression("employees.?[country ==  USA ]").getValue(deptContext);

Here SpEL will return only those employees from the pst 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 apppcation to run and test.

Here is the content of Employee.java file −


package com.tutorialspoint;

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

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

Here is the content of Dept.java file −


package com.tutorialspoint;

import java.util.List;

pubpc class Dept {
   private List<Employee> employees;
   pubpc List<Employee> getEmployees() {
      return employees;
   }
   pubpc 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;

pubpc class MainApp {
   pubpc static void main(String[] args) throws ParseException {
      ExpressionParser parser = new SpelExpressionParser();
      Employee employee1 = new Employee("Robert", "USA");
      Employee employee2 = new Employee("Jupe", "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 pst of employees who are pving in USA
      List<Employee> pst = (List<Employee>)
         parser.parseExpression("employees.?[country ==  USA ]").getValue(deptContext);
      System.out.println(pst);
   }
}

Output


[[Robert, USA], [Jupe, 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> pst = (List<String>)
   parser.parseExpression("employees.![country]").getValue(deptContext);

Here SpEL will return only those employees from the pst 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 apppcation to run and test.

Here is the content of Employee.java file −


package com.tutorialspoint;

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

Here is the content of Dept.java file −


package com.tutorialspoint;

import java.util.List;

pubpc class Dept {
   private List<Employee> employees;
   pubpc List<Employee> getEmployees() {
      return employees;
   }
   pubpc 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;

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

      ExpressionParser parser = new SpelExpressionParser();

      Employee employee1 = new Employee("Robert", "USA");
      Employee employee2 = new Employee("Jupe", "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 pst of countries
      List<String> pst = (List<String>)
         parser.parseExpression("employees.![country]").getValue(deptContext);
      System.out.println(pst);
   }
}

Output


[USA, USA, India]

Spring SpEL - Constructor

SpEL expression supports creating objects within expressions using new operator. We need to pass the fully quapfied 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 apppcation to run and test.

Here is the content of Employee.java file −


package com.tutorialspoint;

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

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

Here is the content of Dept.java file −


package com.tutorialspoint;

import java.util.List;

pubpc class Dept {
   private List<Employee> employees;

   pubpc List<Employee> getEmployees() {
      return employees;
   }
   pubpc void setEmployees(List<Employee> employees) {
      this.employees = employees;
   }
   pubpc 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;

pubpc class MainApp {
   pubpc 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( Jupe , USA ))")
         .getValue(deptContext);
      System.out.println(dept);
   }
}

Output


[[[Robert, USA]]]
[[[Robert, USA], [Jupe, 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 apppcation to run and test.

Here is the content of Employee.java file −


package com.tutorialspoint;

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

   pubpc Employee(String name, String country) {
      this.name = name;
      this.country = country;
   }
   pubpc String getName() {
      return name;
   }
   pubpc void setName(String name) {
      this.name = name;
   }
   pubpc String getCountry() {
      return country;
   }
   pubpc void setCountry(String country) {
      this.country = country;
   }
   pubpc 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;

pubpc class MainApp {
   pubpc 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 apppcation 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;

pubpc class MainApp {
   pubpc 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);
   }
   pubpc 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 pteral 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 apppcation 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;

pubpc class MainApp {
   pubpc 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