How do I access collections members using Spring EL?

In this post you will see another powerful examples of Spring EL. We are going to demonstrate how to use Spring EL to access collection members.

By using Spring EL you can select a single reference member of a collection. You can also select members of collection based on the values of their properties. Another thing you can do is extract properties out of the collection members to create another collection object.

To demonstrate this we are going to create a simple bean / pojo as our collection object. We will create a Book class with some properties (id, title, author).

package org.kodejava.spring.core.el;

public class Book {
    private Long id;
    private String title;
    private String author;
    private String type;

    // Getters & Setters
}

Next, we need to create the spring configuration file. In this configuration we will create a collection of books using the <util:list> element. And we also create a bean with its properties is obtained from one of the collection objects.

<?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:p="http://www.springframework.org/schema/p"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">

    <util:list id="books">
        <bean class="org.kodejava.spring.core.el.Book" p:title="Essential C# 4.0" p:author="Michaelis" />
        <bean class="org.kodejava.spring.core.el.Book" p:title="User Stories Applied" p:author="Mike Cohen" />
        <bean class="org.kodejava.spring.core.el.Book" p:title="Learning Android" p:author="Marco Gargenta" />
        <bean class="org.kodejava.spring.core.el.Book" p:title="The Ruby Programming Language"
              p:author="David Flanagan & Yukihiro Matsumoto" />
        <bean class="org.kodejava.spring.core.el.Book" p:title="Einstein" p:author="Walter Isaacson" />
    </util:list>

    <bean id="book" class="org.kodejava.spring.core.el.Book">
        <property name="title" value="#{books[3].title}" />
        <property name="author" value="#{books[3].author}" />
    </bean>

</beans>

In the configuration above you have seen how we set the title and author of the book bean. We use the square-braces operator ([]) to access collection’s member by their index. It’s look like this:

<property name="title" value="#{books[3].title}"/>
<property name="author" value="#{books[3].author}"/>

Which can be read as: please give me the collection object at index number 3 and take the value of its title and author to be assigned to the book bean. And as you might already know that a collection object in Java is always zero-based index. So this will give us the book with title “The Ruby Programming Language”.

And finally let’s create an example class that run our spring configuration above. It’s simply load the spell-collection.xml configuration we create above. Get a bean from the loaded ApplicationContext and print out its properties, title and author properties.

package org.kodejava.spring.core.el;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class SpELCollectionExample {
    public static void main(String[] args) {
        try (ClassPathXmlApplicationContext context =
                     new ClassPathXmlApplicationContext("spel-collection.xml")) {

            Book book = (Book) context.getBean("book");
            System.out.println("book.getTitle() = " + book.getTitle());
            System.out.println("book.getAuthor() = " + book.getAuthor());
        }
    }
}

Executing the code above will give you the following result:

book.getTitle() = The Ruby Programming Language
book.getAuthor() = David Flanagan & Yukihiro Matsumoto

Maven Dependencies

<dependencies>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>5.3.23</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-beans</artifactId>
        <version>5.3.23</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context-support</artifactId>
        <version>5.3.23</version>
    </dependency>
</dependencies>

Maven Central Maven Central Maven Central

How do I do pattern matching using regular expression in Spring EL?

In this Spring Expression Language example we are going to learn how to use regular expression or regex to check if a text matches a certain pattern. Spring EL support regular expression using the matches operator.

The matches operator will check if the value has a pattern defined by the regex string, and it returns the evaluation result as a boolean value true if the text matches the regex or false if otherwise.

For example, we can use the matches operator to check if the given email address is a valid email address. As can be seen in the following example:

<property name="emailValid" 
          value="#{user.email matches '^[_A-Za-z0-9-]+(.[_A-Za-z0-9-]+)*@[A-Za-z0-9]+(.[A-Za-z0-9]+)*(.[A-Za-z]{2,})$'}"/>

This configuration will evaluate the user.email property to check if the email pattern matches with the given regular expression. If matches then the emailValid property will be set to true otherwise it will be false.

Let’s see the complete example. Here are the spring configuration file, the User bean and a simple class for running the configuration 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.xsd">

    <bean id="user" class="org.kodejava.spring.core.el.User">
        <constructor-arg name="email" value="[email protected]" />
        <property name="emailValid"
                  value="#{user.email matches '^[_A-Za-z0-9-]+(.[_A-Za-z0-9-]+)*@[A-Za-z0-9]+(.[A-Za-z0-9]+)*(.[A-Za-z]{2,})$'}" />
    </bean>

    <bean id="user2" class="org.kodejava.spring.core.el.User">
        <constructor-arg name="email" value="kodejava.at.gmail.dot.com" />
        <property name="emailValid"
                  value="#{user2.email matches '^[_A-Za-z0-9-]+(.[_A-Za-z0-9-]+)*@[A-Za-z0-9]+(.[A-Za-z0-9]+)*(.[A-Za-z]{2,})$'}" />
    </bean>

</beans>

The User bean is a simple pojo with two properties, a string email property and a boolean validEmail property.

package org.kodejava.spring.core.el;

public class User {
    private String email;
    private boolean emailValid;

    public User() {
    }

    public User(String email) {
        this.email = email;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public boolean isEmailValid() {
        return emailValid;
    }

    public void setEmailValid(boolean emailValid) {
        this.emailValid = emailValid;
    }
}

And finally the application class.

package org.kodejava.spring.core.el;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class SpELRegexExample {
    public static void main(String[] args) {
        try (ClassPathXmlApplicationContext context =
                     new ClassPathXmlApplicationContext("spel-regex.xml")) {

            User user = (User) context.getBean("user");
            System.out.println("user.getEmail()     = " + user.getEmail());
            System.out.println("user.isEmailValid() = " + user.isEmailValid());

            User user2 = (User) context.getBean("user2");
            System.out.println("user.getEmail()     = " + user2.getEmail());
            System.out.println("user.isEmailValid() = " + user2.isEmailValid());
        }
    }
}

When we run the code we will obtain the following result:

user.getEmail()     = [email protected]
user.isEmailValid() = true
user.getEmail()     = kodejava.at.gmail.dot.com
user.isEmailValid() = false

Maven Dependencies

<dependencies>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>5.3.23</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-beans</artifactId>
        <version>5.3.23</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context-support</artifactId>
        <version>5.3.23</version>
    </dependency>
</dependencies>

Maven Central Maven Central Maven Central

How do I use ternary operator in Spring EL?

In this example you will learn how to use ternary operator in Spring Expression Language. The ternary operator will evaluate a Spring EL to one value if a condition is true and to another value if the condition is false. Ternary operator is written using the ?: symbols, just as what you do in Java. The test condition is placed on the left side of the ? symbol while the evaluating expression is placed between the : symbol.

As an example, let’s see how to use the ternary operator in a spring configuration 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.xsd">

    <bean id="book1" class="org.kodejava.spring.core.el.Book">
        <property name="type" value="Novel" />
    </bean>
    <bean id="book2" class="org.kodejava.spring.core.el.Book">
        <property name="type" value="#{book1.type != null ? book1.type : 'Novel'}" />
    </bean>
    <bean id="book3" class="org.kodejava.spring.core.el.Book">
        <property name="type" value="#{book1.type ?: 'Novel'}" />
    </bean>

</beans>

In the configuration you’ll see that there are two ways to use the operator. On the book2 bean we use the common usage of the operator. We check if the book1.type is not equal to null, if this is true then we take the book1.type as the value otherwise we just assign the type to 'Novel'.

There are some duplications in the first example. As you can see, we call the boo1.type twice in that line of code. Actually the Spring EL version can give you a shorter one. Instead of doing like before you can just use the ternary operator like what we use in the book3 bean. So we can type book1.type ?: 'Novel'. This will give us the same result.

Having the configuration created you will also need the Book class. So here is the Book class definition.

package org.kodejava.spring.core.el;

public class Book {
    private String type;

    public Book() {
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }
}

Finally, let’s now create a class to run the spring configuration. This class basically just load the spring configuration file spel-ternary.xml and get some beans, the Book bean from the application context and print out the value of its type property.

package org.kodejava.spring.core.el;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class SpELTernaryOperatorExample {
    public static void main(String[] args) {
        try (ClassPathXmlApplicationContext context =
                     new ClassPathXmlApplicationContext("spel-ternary.xml")) {

            Book book1 = (Book) context.getBean("book1");
            Book book2 = (Book) context.getBean("book2");
            Book book3 = (Book) context.getBean("book3");

            System.out.println("book1.getType() = " + book1.getType());
            System.out.println("book2.getType() = " + book2.getType());
            System.out.println("book3.getType() = " + book3.getType());
        }
    }
}

And here are the execution output that you’ll get.

book1.getType() = Novel
book2.getType() = Novel
book3.getType() = Novel

Maven Dependencies

<dependencies>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>5.3.23</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-beans</artifactId>
        <version>5.3.23</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context-support</artifactId>
        <version>5.3.23</version>
    </dependency>
</dependencies>

Maven Central Maven Central Maven Central

How do I use logical expression in Spring EL?

In the previous example you have learnt How do I compare values in Spring EL?. Where you saw how to compare two simple values for equality, less-than or greater-than, etc. In practice, you might need to combine one or more of this comparison into a more complex logical expressions.

Spring EL also provides several operators that can be used to do this kind of logical operations. These operators are shown in the following table.

Operator Description
and A logical AND operation; the result will be true of both sides are true.
or A logical OR operation; the result will be true if at least on side is true.
not or ! A logical NOT operation; it will negates the expression value.

Here is an example using the logical and operator in the spring configuration file:

<property name="largeGlass" value="#{smallGlass.maxVolume ge 20 and smallGlass.maxVolume le 30}"/>

The configuration above will set the largeGlass property above to true if the glass maxVolume is greater-that-or-equal to 20 and less-than-or-equal to 30. It will only be considered as a large glass if the volume is between 20 and 30. So we use the logical and operator in that expression to evaluate the value for the largeGlass property. Now let’s see the complete example.

First let’s define the MyOtherGlass pojo.

package org.kodejava.spring.core.el;

public class MyOtherGlass {
    private boolean empty;
    private boolean halfEmpty;
    private int volume;
    private int maxVolume;
    private boolean largeGlass;

    public MyOtherGlass() {
    }

    public MyOtherGlass(int volume, int maxVolume) {
        this.volume = volume;
        this.maxVolume = maxVolume;
    }

    public boolean isEmpty() {
        return empty;
    }

    public void setEmpty(boolean empty) {
        this.empty = empty;
    }

    public boolean isHalfEmpty() {
        return halfEmpty;
    }

    public void setHalfEmpty(boolean halfEmpty) {
        this.halfEmpty = halfEmpty;
    }

    public int getVolume() {
        return volume;
    }

    public void setVolume(int volume) {
        this.volume = volume;
    }

    public int getMaxVolume() {
        return maxVolume;
    }

    public void setMaxVolume(int maxVolume) {
        this.maxVolume = maxVolume;
    }

    public boolean isLargeGlass() {
        return largeGlass;
    }

    public void setLargeGlass(boolean largeGlass) {
        this.largeGlass = largeGlass;
    }
}

After creating the pojo, let’s now create our spring configuration file where we define the smallGlass bean and the largeGlass bean.

<?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="smallGlass" class="org.kodejava.spring.core.el.MyOtherGlass">
        <constructor-arg name="volume" value="5" />
        <constructor-arg name="maxVolume" value="10" />
        <property name="largeGlass" value="#{smallGlass.maxVolume ge 20 and smallGlass.maxVolume le 30}" />
    </bean>
    <bean id="largeGlass" class="org.kodejava.spring.core.el.MyOtherGlass">
        <constructor-arg name="volume" value="5" />
        <constructor-arg name="maxVolume" value="30" />
        <property name="largeGlass" value="#{largeGlass.maxVolume ge 20 and largeGlass.maxVolume le 30}" />
    </bean>

</beans>

And finally let’s create a class to run this configuration file in the console:

package org.kodejava.spring.core.el;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class SpELLogicalExpression {
    public static void main(String[] args) {
        try (ClassPathXmlApplicationContext context =
                     new ClassPathXmlApplicationContext("spel-logical-expression.xml")) {

            MyOtherGlass smallGlass =
                    (MyOtherGlass) context.getBean("smallGlass");
            MyOtherGlass largeGlass =
                    (MyOtherGlass) context.getBean("largeGlass");

            System.out.println("smallGlass.isLargeGlass() = " + smallGlass.isLargeGlass());
            System.out.println("largeGlass.isLargeGlass() = " + largeGlass.isLargeGlass());
        }
    }
}

This code will give you the following output when executed:

smallGlass.isLargeGlass() = false
largeGlass.isLargeGlass() = true

Maven Dependencies

<dependencies>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>5.3.23</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-beans</artifactId>
        <version>5.3.23</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context-support</artifactId>
        <version>5.3.23</version>
    </dependency>
</dependencies>

Maven Central Maven Central Maven Central

How do I compare values in Spring EL?

In Spring EL you can compare two values to know if they are equals, is greater or smaller than the other value. For these kinds of comparison, below are the list of operators supported by Spring EL, as expected it supports the same operators as in the Java programming language.

The Spring Expression Language comparison operators includes:

Symbol Textual Description
== eq Double-equal operator to compare two values for equality.
< lt Less-than operator to compare if a value is smaller than the other value.
> gt Greater-than operator to compare if a value is greater than the other value.
<= le Less-than-or-equal operator to compare if a value is smaller or equals to another value.
>= ge Greater-than-or-equal operator to compare if a value is greater or equals to another value.

For example, you can use the double-equal operator like the following XML configuration:

<property name="empty" value="#{myGlass.volume == 0}"/>

It means that we are going to set the empty property to be either a boolean true or false if the value of myGlass.volume is equal to 0 or not. The double-equal symbol is not a problem when use in the XML document. But you will understand right away that you can’t use the less-than (<) or greater-than (>) symbol in XML, because the characters is used to define the XML document itself.

To make it work we must use the textual version of these operators. For example, you will use the lt instead of < symbol or gt instead of the > symbol as can be seen in the table above. Now let’s see an example in the spring configuration 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.xsd">

    <bean id="myGlass" class="org.kodejava.spring.core.el.MyGlass">
        <constructor-arg name="volume" value="5" />
        <constructor-arg name="maxVolume" value="10" />
        <property name="empty" value="#{myGlass.volume == 0}" />
        <property name="halfEmpty" value="#{(myGlass.maxVolume / 2) le myGlass.volume}" />
    </bean>

</beans>

In the above configuration we have a bean called myGlass. We instantiate it with two constructor values, the volume was set to 5 and the maxVolume was set to 10. To set the value of the empty and halfEmpty property we use the double-equal and less-than-equal operator to check the value of the volume and maxVolume properties.

After you have the spring configuration, let’s create the MyGlass bean and an application to run the configuration file. The bean is just a simple class with some properties and a collections of getters and setters.

package org.kodejava.spring.core.el;

public class MyGlass {
    private boolean empty;
    private boolean halfEmpty;
    private int volume;
    private int maxVolume;

    public MyGlass() {
    }

    public MyGlass(int volume, int maxVolume) {
        this.volume = volume;
        this.maxVolume = maxVolume;
    }

    public boolean isEmpty() {
        return empty;
    }

    public void setEmpty(boolean empty) {
        this.empty = empty;
    }

    public boolean isHalfEmpty() {
        return halfEmpty;
    }

    public void setHalfEmpty(boolean halfEmpty) {
        this.halfEmpty = halfEmpty;
    }

    public int getVolume() {
        return volume;
    }

    public void setVolume(int volume) {
        this.volume = volume;
    }

    public int getMaxVolume() {
        return maxVolume;
    }

    public void setMaxVolume(int maxVolume) {
        this.maxVolume = maxVolume;
    }
}

To run the spring configuration above you can create the SpELCompareValue class below.

package org.kodejava.spring.core.el;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class SpELCompareValue {
    public static void main(String[] args) {
        try (ClassPathXmlApplicationContext context = new
                ClassPathXmlApplicationContext("spel-compare-value.xml")) {
            MyGlass glass = (MyGlass) context.getBean("myGlass");
            System.out.println("glass.getVolume()   = " + glass.getVolume());
            System.out.println("glass.isEmpty()     = " + glass.isEmpty());
            System.out.println("glass.isHalfEmpty() = " + glass.isHalfEmpty());
        }
    }
}

And when you executed the code above you will get the following output:

glass.getVolume()   = 5
glass.isEmpty()     = false
glass.isHalfEmpty() = true

Maven Dependencies

<dependencies>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>5.3.23</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-beans</artifactId>
        <version>5.3.23</version>
    </dependency>
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context-support</artifactId>
        <version>5.3.23</version>
    </dependency>
</dependencies>

Maven Central Maven Central Maven Central