Spring Expression Language Examples

0

In this article, we will see some examples of Spring Expression Language (SpEL). So what is Spring Expression Language? It is an expression language that supports dynamic evaluation of a property, or any property in the object graph. It also allows us to manipulate the object graph at runtime using expression. This article’s purpose is to introduce you to the possibilities of spring expression language.

Let’s get down to the examples and you will know what I am talking about.

This example uses the following frameworks:

  1. Maven 3.2.3
  2. Spring 4.1.5.RELEASE
  3. Eclipse  as the IDE, version Luna 4.4.1.

Dependencies

Add the following dependencies:

  1. spring-core
  2. spring-context
  3. spring-beans

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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.javarticles.spring</groupId>
	<artifactId>springListExample</artifactId>
	<version>0.0.1-SNAPSHOT</version>

	<dependencies>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>${spring.version}</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-beans</artifactId>
			<version>${spring.version}</version>
		</dependency>
	</dependencies>

	<properties>
		<spring.version>3.2.3.RELEASE</spring.version>
	</properties>

</project>

Expression Support in Spring Context XML

We can use spring expressions within the XML context itself to simplify the configuration.

A bit about our example and then will follow the POJO classes.

Our example consists of a training program based on a tutorial composed of some technical topics. The training will be conducted on one single topic.

Topic:

package com.javarticles.spring;

public class Topic {
    private String name;
    
    public Topic(){}

    public Topic(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

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

Tutorial:

package com.javarticles.spring;

import java.util.ArrayList;
import java.util.List;

public class Tutorial {
    private String name;
    
    private List<?> topicsList = new ArrayList<>();

    public String getName() {
        return name;
    }

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

    public List<?> getTopicsList() {
        return topicsList;
    }

    public void setTopicsList(List<?> topicsList) {
        this.topicsList = topicsList;
    }

    public String toString() {
        return name + topicsList;
    }
    
}

Training:

package com.javarticles.spring;

public class Training {
    private Topic topic;

    public Topic getTopic() {
        return topic;
    }

    public void setTopic(Topic topic) {
        this.topic = topic;
    }
}

In the context XML, we will define couple of technical topics javaCore and ScalaBasics, tutorial and training.

SpEL expressions can be used with XML while defining the beans. The syntax is #{<expression string>}.
Our training bean’s topic is configured using #{tutorial.topicsList[1]}. It retrieves the second topic from the tutorial bean’s list of topics and sets the topic property.

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.xsd">

	<bean id="tutorial" class="com.javarticles.spring.Tutorial">
		<property name="topicsList">
			<list>
				<ref local="javaCore" />
				<ref local="scalaBasics" />
			</list>
		</property>
	</bean>
		
	<bean id="javaCore" class="com.javarticles.spring.Topic">
		<property name="name" value="JavaCore" />
	</bean>
	
	<bean id="scalaBasics" class="com.javarticles.spring.Topic">
		<property name="name" value="ScalaBasics" />
	</bean>	
	
	<bean id="training" class="com.javarticles.spring.Training">
		<property name="topic" value="#{tutorial.topicsList[1]}"/>
	</bean>
	
</beans>

SpringExpressionXmlContextExample:

package com.javarticles.spring;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class SpringExpressionXmlContextExample {
    public static void main(String[] args) {
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
                "applicationContext.xml");
        try {
            Training training = (Training) context.getBean("training");
            System.out.println(training.getTopic());           
        } finally {
            context.close();
        }
    }
}

Output:

ScalaBasics

Spring Expressions using Annotation

SpEL expressions can also be used with annotation-based configuration metadata for defining the beans. The @Value annotation can be placed on fields, methods and method/constructor parameters to specify a default value.

To demonstrate the example, we have introduced another member defaultTopic to our Training bean. We have used spring expression to set the defaultTopic.

Training:

package com.javarticles.spring;

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

public class Training {
    private Topic topic;
    
    @Value("#{tutorial.topicsList[0]}")
    private Topic defaultTopic;

    public Topic getTopic() {
        return topic;
    }

    public void setTopic(Topic topic) {
        this.topic = topic;
    }
    
    public Topic getDefaultTopic() {
        return defaultTopic;
    }
}

Adding context:component-scan element to the context XML so that the annotations are scanned and evaluated.

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"
	xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
	http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd">

     <context:component-scan base-package="com.javarticles.spring" />

	<bean id="tutorial" class="com.javarticles.spring.Tutorial">
		<property name="topicsList">
			<list>
				<ref local="javaCore" />
				<ref local="scalaBasics" />
			</list>
		</property>
	</bean>
		
	<bean id="javaCore" class="com.javarticles.spring.Topic">
		<property name="name" value="JavaCore" />
	</bean>
	
	<bean id="scalaBasics" class="com.javarticles.spring.Topic">
		<property name="name" value="ScalaBasics" />
	</bean>	
	
	<bean id="training" class="com.javarticles.spring.Training">
		<property name="topic" value="#{tutorial.topicsList[0]}"/>
	</bean>
	
</beans>

Let’s test whether defaultTopic is set.

SpringExpressionXmlContextExample:

package com.javarticles.spring;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class SpringExpressionXmlContextExample {
    public static void main(String[] args) {
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
                "applicationContext.xml");
        try {
            Training training = (Training) context.getBean("training");
            System.out.println(training.getTopic());  

            System.out.println(training.getDefaultTopic());         
        } finally {
            context.close();
        }
    }
}

Output:

ScalaBasics
JavaCore

Example of Spring Expression Language Parser

The SpEL can also be used as a standalone component using the expression parser org.springframework.expression.spel.standard.SpelExpressionParser.

For example,

SpringExpressionParserExample:

package com.javarticles.spring;

import java.util.Arrays;

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

public class SpringExpressionParserExample {
    public static void main(String[] args) {
        SpelExpressionParser parser = new SpelExpressionParser();
        Expression exp = parser.parseExpression("'Just a string value'");
        String message = (String) exp.getValue();
        System.out.println(message);
    }
}

Output:

Just a string value

Let’s look at few more examples.

Calling Method using Spring ExpressionParser

In this example, we call String‘s substring(), length().

SpringExpressionParserExample:

package com.javarticles.spring;

import java.util.Arrays;

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

public class SpringExpressionParserExample {
    public static void main(String[] args) {
        SpelExpressionParser parser = new SpelExpressionParser();
        Expression exp = parser.parseExpression("'Just a string value'");
        String message = (String) exp.getValue();
        System.out.println(message);
        
        System.out.println(parser.parseExpression("'Just a string value'.substring(5)").getValue());
        
        System.out.println(parser.parseExpression("'Just a string value'.length()").getValue());
        
        System.out.println(parser.parseExpression("'Just a string value'.substring('Just '.length())").getValue());        
    }
}

Output:

Just a string value
a string value
19
a string value

Access JavaBean Properties using Spring ExpressionParser

Let’s access couple of JavaBean properties class and bytes of String object.

SpringExpressionParserExample:

package com.javarticles.spring;

import java.util.Arrays;

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

public class SpringExpressionParserExample {
    public static void main(String[] args) {
        SpelExpressionParser parser = new SpelExpressionParser();
        Expression exp = parser.parseExpression("'Just a string value'");
        String message = (String) exp.getValue();
        System.out.println(message);
        
        System.out.println(parser.parseExpression("'Just a string value'.substring(5)").getValue());
        
        System.out.println(parser.parseExpression("'Just a string value'.length()").getValue());
        
        System.out.println(parser.parseExpression("'Just a string value'.substring('Just '.length())").getValue());
        
        System.out.println(parser.parseExpression("'Just a string value'.class").getValue());
        
        System.out.println(parser.parseExpression("'Just a string value'.bytes").getValue());        
    }
}

Output:

Just a string value
a string value
19
a string value
class java.lang.String
[[email protected]

Calling Constructor using Spring ExpressionParser

We can create an object by calling the constructor of the class in the spring expression. For example, 'new com.javarticles.spring.Topic('Java')'.

parser.parseExpression("new com.javarticles.spring.Topic('Java')").getValue(Topic.class)

SpringExpressionParserExample:

package com.javarticles.spring;

import java.util.Arrays;

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

public class SpringExpressionParserExample {
    public static void main(String[] args) {
        SpelExpressionParser parser = new SpelExpressionParser();
        Expression exp = parser.parseExpression("'Just a string value'");
        String message = (String) exp.getValue();
        System.out.println(message);
        
        System.out.println(parser.parseExpression("'Just a string value'.substring(5)").getValue());
        
        System.out.println(parser.parseExpression("'Just a string value'.length()").getValue());
        
        System.out.println(parser.parseExpression("'Just a string value'.substring('Just '.length())").getValue());
        
        System.out.println(parser.parseExpression("'Just a string value'.class").getValue());
        
        System.out.println(parser.parseExpression("'Just a string value'.bytes").getValue());
        
        System.out.println(parser.parseExpression("new com.javarticles.spring.Topic('Java')").getValue(Topic.class).getClass());        
    }
}

Output:

Just a string value
a string value
19
a string value
class java.lang.String
[[email protected]
class com.javarticles.spring.Topic

Download the source code

This was an introduction to spring expression language.

You can download the source code here: springExpressionExamples.zip
Share.

Comments are closed.