Learn Spring By Example – Spring Expression Language (SpEL)

Hi friends,

Spring 3 introduced the Spring Expression Language (SpEL), a powerful expression language, used to wire values into bean’s properties. It’s an expression language similar to other ELs, that supports querying and manipulating an object graph at runtime.

The Spring expression language (SpEL) can handle following features:

  • Literal expressions
  • Boolean and relational operators
  • Regular expressions
  • Class expressions
  • Accessing properties, arrays, lists, maps
  • Method invocation
  • Relational operators
  • Assignment
  • Calling constructors
  • Templated expressions
  • Collection selection
  • Collection projection
  • User defined functions
  • Variables
  • Ternary operator
  • Inline lists
  • Array construction
  • Bean references

SpEL can be configured in spring configuration files and bean classes using XML and java annotations respectively.

XML Based Configuration


Literal Values

We can set literal values of any data type to bean properties using SpEL.

<property name="age"value="#{35}"/>

<property name="name"value="#{'Deepesh'}"/>

<property name="message" value="My name is #{'Deepesh'} and I'm #{27} years old."/>

<property name="amount" value="#{5e3}"/>

<property name="isObsolete" value="#{true}"/>

<property name="length" value="#{50.35}"/>

Bean References

We can refer other spring beans using SpEL.

<property name="address" value="#{office_address}"/>

which is same as

<property name="address" ref="office_address"/>

Yes indeed, the outcome from both the above expressions is same.

Property References

Properties of other beans can be referred using SpEL.

<bean id="author">
<property name="name" value="Rudyard Kipling"/>
</bean>

<bean id="book">
<property name="author_name" value="#{author.name}"/>
</book>

which is same as

Book book = new Book();
book.setAuthor_name(author.getName());

Method References

This is how a method of another bean is referred.

<property name="hours" value="#{employee.workingHours()}"/>

<property name="empName" value="#{employee.getFullName().toUpperCase()}"/>

Safe Navigation operator

What we do if the above method employee.getFullName() returns null? Obviously we’ll get a NullPointerException when making a null value to represent in upper case. The Safe Navigation operator is used to avoid a NullPointerException. The operator is represented using “?.” syntax and comes from the Groovy language.

This operator makes sure that the item to its left isn’t null before accessing the thing to its right. Whenever the above method employee.getFullName() returns null, the SpEL wouldn’t try to execute toUpperCase() on it.

<property name="empName" value="#{employee.getFullName()?.toUpperCase()}"/>

Collection Selection

Selection is another expression language feature that allows you to select entries from a collection. The collection selection is represented by “?.[collectionExpression]” operator. We write the expression within the square brackets.

For writing conditions, obviously we need arithmetic operators and as luck would have it, SpEL is equipped with all basic arithmetic and logical operators. And fortunately, SpEL can handle both symbolic and textual form of most of all the operators.

<property name="subjects" value="#{subjectList}"/>

<property name="topSubjects" value="#{subjectList.?[id gt 111 and id lt 113]}"/>

Collection selection can have another syntax.

<property name="mycity" value="#{cities[2]}"/>

where “cities” is a collection of type city.

Arithmetic Operations

<property name="mrp"value="#{counter.total+25}"/>

List of Arithmetic and Logical Operators

spring_spel_op

Collection Projection

Collection projection involves collecting a particular property from each of the members of a collection into a new collection. Projection allows a collection to drive the evaluation of a sub-expression and the result is a new collection. The syntax for projection is “![projectionExpression]“.

Here we list the names of tough subjects.

<property name="toughSubjects" value="#{subjectList.![id+':'+name]}"/>

Ternary Operations

Ternary operator is an alternative to the Java if/then/else syntax. The SpEL supports this operator.

<bean id="rudyard">
....
</bean>

<bean id="robert">
....
</bean>

<bean id="library">
<property name="author" value="#{book.getName()=='Jungle Book'?rudyard:robert}"/>
</bean>

Working With Types

If we need to invoke a static method or reference a constant of a class, the T() operator is used.

<property name="const" value="#{T(java.lang.Math).E}" />

Annotation-based configuration

The @Value annotation can be placed on fields, methods and method/constructor parameters to specify a default value. All the above said operators are worked with annotation based configuration as well.

@Value("Guitar")
private String name;

@Value("#{piano.sound}")
private String sound;

An Example

Here, let’s see a simple example of SpEL using XML configuration.

Student Bean – Student.java

package com.spring.spel;

import java.util.List;

public class Student {
	private String name;
	private List<Subject> subjects;
	private List<Subject> topSubjects;
	private List<String> toughSubjects;

	public void setToughSubjects(List<String> toughSubjects) {
		this.toughSubjects = toughSubjects;
	}

	public List<String> getToughSubjects() {
		return toughSubjects;
	}

	public void setTopSubjects(List<Subject> topSubjects) {
		this.topSubjects = topSubjects;
	}

	public List<Subject> getTopSubjects() {
		return topSubjects;
	}

	public void setSubjects(List<Subject> subjects) {
		this.subjects = subjects;
	}

	public List<Subject> getSubjects() {
		return subjects;
	}

	public String getName() {
		return name;
	}

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

Subject Bean – Subject.java

package com.spring.spel;

public class Subject {
	private String name;
	private int id;

	public void setId(int id) {
		this.id = id;
	}

	public int getId() {
		return id;
	}

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

	public String getName() {
		return name;
	}
}

Configuration File – StudentSubject.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:util="http://www.springframework.org/schema/util"
	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:p="http://www.springframework.org/schema/p"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd">


	<util:list id="subjectList">
		<bean class="com.spring.spel.Subject" p:id="110" p:name="Sociology" />
		<bean class="com.spring.spel.Subject" p:id="111" p:name="Physics" />
		<bean class="com.spring.spel.Subject" p:id="112" p:name="Mathematics" />
		<bean class="com.spring.spel.Subject" p:id="113" p:name="Biology" />
	</util:list>
	
	<bean id="ebi" class="com.spring.spel.Student">
		<property name="name" value="#{'Ebi Mathew'}" />
		<property name="subjects" value="#{subjectList}"/>
		<property name="topSubjects" value="#{subjectList.?[id gt 111 and id lt 113]}"/>
		<property name="toughSubjects" value="#{subjectList.?[id le 111].![id+':'+name]}"/>
	</bean>
</beans>

Main Class – StudentSubjectImpl.java

package com.spring.spel;

import net.roseindia.ApplicationUtils;

public class StudentSubjectImpl extends ApplicationUtils {
	public static void main(String[] args) {
		Student student = getBean("com/spring/spel/StudentSubject.xml", "ebi");
		System.out.println("Name: " + student.getName());
		System.out.println("\nAll Subjects:");
		for (Subject subject : student.getSubjects()) {
			System.out.println("Id: " + subject.getId() + "\tName: "
					+ subject.getName());
		}
		System.out.println("\nTop Subjects:");
		for (Subject subject : student.getTopSubjects()) {
			System.out.println("Id: " + subject.getId() + "\tName: "
					+ subject.getName());
		}
		System.out.println("\nTough Subjects:");
		for (String subjects : student.getToughSubjects()) {
			System.out.println(subjects);
		}
	}
}

Output

Name: Ebi Mathew

All Subjects:
Id: 110	Name: Sociology
Id: 111	Name: Physics
Id: 112	Name: Mathematics
Id: 113	Name: Biology

Top Subjects:
Id: 112	Name: Mathematics

Tough Subjects:
110:Sociology
111:Physics

File Structure

spring_spel_file

List of Operators

Finally, we can see the whole list of operators that SpEL supports.

spring_spel_oplist

Conclusion

Here we’ve discussed about the Spring Expression Language (SpEL), a potential EL which has innumerably infinite features and supports arithmetic, relational, logical, conditional operators.

Thanks.

About these ads

2 Comments

    Trackbacks

    1. Links & reads for 2013 Week 15 | Martin's Weekly Curations
    2. Fake oakleys

    Leave a Reply

    Fill in your details below or click an icon to log in:

    WordPress.com Logo

    You are commenting using your WordPress.com account. Log Out / Change )

    Twitter picture

    You are commenting using your Twitter account. Log Out / Change )

    Facebook photo

    You are commenting using your Facebook account. Log Out / Change )

    Google+ photo

    You are commenting using your Google+ account. Log Out / Change )

    Connecting to %s

    Follow

    Get every new post delivered to your Inbox.

    Join 455 other followers

    %d bloggers like this: