How do I combine filter and projection operation in Spring EL?

Using Spring Expression Language (SpEL) we can filter a collection based on some criteria. We can also create a projection of a collection by collecting only a particular property from the collection objects.

Now you know that you have two good features of SpEL that are really powerful to use when working with collection objects manipulation. But you are wondering how to combine both of these filter and projection in one expression. Can you do this in Spring EL? The answer is yes! You can combine them both in one expression. Let’s see an example below.

We are going to use the same configuration used in the previous example:

<?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.example.spring.model.Book"
              p:title="Essential C# 4.0" p:author="Michaelis" p:pages="450"/>
        <bean class="org.kodejava.example.spring.model.Book"
              p:title="User Stories Applied" p:author="Mike Cohen" p:pages="268"/>
        <bean class="org.kodejava.example.spring.model.Book"
              p:title="Learning Android" p:author="Marco Gargenta" p:pages="245"/>
        <bean class="org.kodejava.example.spring.model.Book"
              p:title="The Ruby Programming Language"
              p:author="David Flanagan &amp; Yukihiro Matsumoto" p:pages="250"/>
        <bean class="org.kodejava.example.spring.model.Book"
              p:title="Einstein" p:author="Walter Isaacson" p:pages="1000"/>
    </util:list>

    <bean id="library" class="org.kodejava.example.spring.model.Library">
        <property name="bookTitles" value="#{books.?[pages gt 250].![title]}"/>
    </bean>
</beans>

In the configuration above, when we define the library bean we set its bookTitles property using the filtering and projection operator. First we take only books that have more that 250 pages and then we create the projection that contains only the book title. So this expression give us all the book’s title of a book that has more than 250 pages.

To make the example complete here again the definition of the Book and the Library class.

package org.kodejava.example.spring.model;

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

    //
    // Getters & Setters
    //
}
package org.kodejava.example.spring.model;

import java.util.List;

public class Library {
    private List<Book> books;
    private List<String> bookTitles;
    
    //
    // Getters & Setters
    //
}

The main class the run the configuration file:

package org.kodejava.example.spring;

import org.kodejava.example.spring.model.Library;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class SpELFilterProjectionExample {
    public static void main(String[] args) {
        ApplicationContext context =
                new ClassPathXmlApplicationContext("spel-filter-projection.xml");

        Library library = context.getBean("library", Library.class);

        for (String title : library.getBookTitles()) {
            System.out.println("title = " + title);
        }
    }
}

The result of the code snippet:

INFO: Loading XML bean definitions from class path resource [spel-filter-projection.xml]
title = Essential C# 4.0
title = User Stories Applied
title = Einstein

How do I create a projection of a collection using Spring EL?

In this example you will learn how to create a projection of a collection object. Using projection we can create a new collection with only a specific property from the original collection.

As an example, instead of returning a collection of Book objects we would like only to have the titles of the books. To do this we can use the Spring EL projection operator. The symbol use for this operator is ![].

Let’s begin by creating 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"
       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.example.spring.model.Book"
              p:title="Essential C# 4.0" p:author="Michaelis" p:pages="450"/>
        <bean class="org.kodejava.example.spring.model.Book"
              p:title="User Stories Applied" p:author="Mike Cohen" p:pages="268"/>
        <bean class="org.kodejava.example.spring.model.Book"
              p:title="Learning Android" p:author="Marco Gargenta" p:pages="245"/>
        <bean class="org.kodejava.example.spring.model.Book"
              p:title="The Ruby Programming Language"
              p:author="David Flanagan &amp; Yukihiro Matsumoto" p:pages="250"/>
        <bean class="org.kodejava.example.spring.model.Book"
              p:title="Einstein" p:author="Walter Isaacson" p:pages="1000"/>
    </util:list>

    <bean id="library" class="org.kodejava.example.spring.model.Library">
        <property name="bookTitles" value="#{books.![title]}"/>
    </bean>
</beans>

Here are the definition of the Book and Library class. The getters and setters methods were removed for simplicity of the snippet.

package org.kodejava.example.spring.model;

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

    //
    // Getters & Setters
    //
}
package org.kodejava.example.spring.model;

import java.util.List;

public class Library {
    private List<Book> books;
    private List<String> bookTitles;

    //
    // Getters & Setters
    //
}

Now, let’s talk about the Spring configuration above. The configuration was start by creating a collection of Books using the <util:elements>. The part that use the projection operator is this part of the configuration:

<bean id="library" class="org.kodejava.example.spring.model.Library">
    <property name="bookTitles" value="#{books.![title]}"/>
</bean>

The bean element above create a library bean of type org.kodejava.example.spring.model.Library. We assign the bean’s bookTitles property with values that are a projection of the +books+ collection where we take only the title of the books. ![projectionExpression] is the syntax of the projection operator.

The code snippet below will demonstrate and run our configuration file and print out the result:

package org.kodejava.example.spring;

import org.kodejava.example.spring.model.Library;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class SpELProjectionExample {
    public static void main(String[] args) {
        ApplicationContext context =
                new ClassPathXmlApplicationContext("spel-projection.xml");

        Library library = context.getBean("library", Library.class);

        for (String title : library.getBookTitles()) {
            System.out.println("title = " + title);
        }
    }
}

And here are the result:

INFO: Loading XML bean definitions from class path resource [spel-projection.xml]
title = Essential C# 4.0
title = User Stories Applied
title = Learning Android
title = The Ruby Programming Language
title = Einstein

How do I filter collection members based on some criteria using Spring EL?

In some of the previous example you have seen that we use the square-braces [] operator to select items from collection. In this blog post you will learn how to filter some members of a collection with a certain criteria while using the Spring EL. To do this Spring EL give you another special operator, the filter operator which can be typed like .?[]. Where you can define the filter criteria inside the braces.

Beside the filter operator .?[]> there are also operator that can select the first and the last matching items from collection. You can use the .^[] for selecting the first match and the .$[] operator to select the last match items from collection respectively.

As an example we will demonstrate here that we want to find a collection of books that have pages more than 250 and assign it to Library bean’s books properties. So let’s begin by defining a class called Book and Library which will have the following properties:

package org.kodejava.example.spring.model;

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

    //
    // Getters & Setters
    //

    @Override
    public String toString() {
        return "Book{" +
                "title='" + title + ''' +
                ", author='" + author + ''' +
                ", pages=" + pages +
                '}';
    }
}
package org.kodejava.example.spring.model;

import java.util.List;

public class Library {
    private List books;

    // 
    // Getter & Setter
    //
}

After creating the Book and the Library class let’s now create the Spring configuration file for our demo. We will create a file and call it as spel-select-collection.xml with the following lines of configuration in it.

<?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:p="http://www.springframework.org/schema/p"
       xmlns:util="http://www.springframework.org/schema/util"
       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.example.spring.model.Book"
              p:title="Essential C# 4.0" p:author="Michaelis" p:pages="450"/>
        <bean class="org.kodejava.example.spring.model.Book"
              p:title="User Stories Applied" p:author="Mike Cohen" p:pages="268"/>
        <bean class="org.kodejava.example.spring.model.Book"
              p:title="Learning Android" p:author="Marco Gargenta" p:pages="245"/>
        <bean class="org.kodejava.example.spring.model.Book"
              p:title="The Ruby Programming Language"
              p:author="David Flanagan &amp; Yukihiro Matsumoto" p:pages="250"/>
        <bean class="org.kodejava.example.spring.model.Book"
              p:title="Einstein" p:author="Walter Isaacson" p:pages="1000"/>
    </util:list>

    <bean id="lib1" class="org.kodejava.example.spring.model.Library">
        <property name="books" value="#{books.?[pages gt 250]}"/>
    </bean>

    <bean id="lib2" class="org.kodejava.example.spring.model.Library">
        <property name="books" value="#{books.^[pages gt 250]}"/>
    </bean>

    <bean id="lib3" class="org.kodejava.example.spring.model.Library">
        <property name="books" value="#{books.$[pages gt 250]}"/>
    </bean>
</beans>

The first thing that you can see in the configuration above is the <util-list> where we create a list of Book beans. Next we have three beans definition of the type Library where the books property was assigned with a collection of beans selected from the books list.

The lib1 will contains books that have pages more than 250. The lib2 will contains the first book found to have more than 250 pages while the lib3 will contains the last book found to have more than 250 pages.

Below is the code that will run our configuration file and the example output it will produce.

package org.kodejava.example.spring;

import org.kodejava.example.spring.model.Book;
import org.kodejava.example.spring.model.Library;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class SpELFilterCollection {
    public static void main(String[] args) {
        ApplicationContext context =
                new ClassPathXmlApplicationContext("spel-filter-collection.xml");

        System.out.println("Library 1");
        Library lib1 = (Library) context.getBean("lib1");
        for (Book book : lib1.getBooks()) {
            System.out.println("    Book = " + book);
        }

        System.out.println("Library 2");
        Library lib2 = (Library) context.getBean("lib2");
        for (Book book : lib2.getBooks()) {
            System.out.println("    Book = " + book);
        }

        System.out.println("Library 3");
        Library lib3 = (Library) context.getBean("lib3");
        for (Book book : lib3.getBooks()) {
            System.out.println("    Book = " + book);
        }
    }
}
INFO: Loading XML bean definitions from class path resource [spel-filter-collection.xml]
Library 1
    Book = Book{title='Essential C# 4.0', author='Michaelis', pages=450}
    Book = Book{title='User Stories Applied', author='Mike Cohen', pages=268}
    Book = Book{title='Einstein', author='Walter Isaacson', pages=1000}
Library 2
    Book = Book{title='Essential C# 4.0', author='Michaelis', pages=450}
Library 3
    Book = Book{title='Einstein', author='Walter Isaacson', pages=1000}

How do I read system environment variables in Spring EL?

Previously you have seen that we can load properties file and read a value from it in this example: How do I read a value from properties file using Spring EL?. In this example you will learn how to read a special properties available to Spring EL. These properties includes the systemEnvironment and systemProperties.

The systemEnvironment property contains all the environment variables on the machine where the program is running. Meanwhile, the systemProperties contains all the properties that we set in Java when the application started, using the -D argument. Let’s see how to access both of these properties in the following 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="program1"
          class="org.kodejava.example.spring.model.Program">
        <property name="logPath"
                  value="#{systemProperties['APP.LOG_PATH']}"/>
    </bean>
    <bean id="program2"
          class="org.kodejava.example.spring.model.Program">
        <property name="logPath"
                  value="#{systemEnvironment['HOME']}"/>
    </bean>
</beans>

In the configuration above we have two beans of Program. We set the logPath properties using a different property source. In the program1 bean we use systemProperties['APP.LOG_PATH']. Using this method the value will be pass to our program using the -DAPP.LOG_PATH=/Users/wsaryada/tmp when we are executing the program. While the program2 bean’s logPath is read from user’s home directory property available through the systemEnvironment variables.

To make the Spring configuration works you’ll need the Program class. So here is the class definition.

package org.kodejava.example.spring.model;

public class Program {
    private String logPath;

    public Program() {
    }

    public String getLogPath() {
        return logPath;
    }

    public void setLogPath(String logPath) {
        this.logPath = logPath;
    }
}

Finally, let’s create a simple class to execute the Spring configuration file above and see the result of the code.

package org.kodejava.example.spring;

import org.kodejava.example.spring.model.MyDataSource;
import org.kodejava.example.spring.model.Program;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class SpELEnvironment {
    public static void main(String[] args) {
        ApplicationContext context =
                new ClassPathXmlApplicationContext("spel-environment.xml");

        Program program1 = (Program) context.getBean("program1");
        System.out.println("program.getLogPath() = " + program1.getLogPath());

        Program program2 = (Program) context.getBean("program2");
        System.out.println("program.getLogPath() = " + program2.getLogPath());
    }
}

The code will print the following result:

INFO: Loading XML bean definitions from class path resource [spel-environment.xml]
program.getLogPath() = /Users/wsaryada/tmp
program.getLogPath() = /Users/wsaryada

How do I read a value from properties file using Spring EL?

In the previous two examples you have seen how to access member of a collection and access a map element using the square-braces [] operator in Spring EL. In this example you will see how to use the [] operator to read a value from a properties file or java.util.Properties. Let’s say we have a database properties file called database.properties with the following entries in it:

jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost/mydb
jdbc.username=root
jdbc.password=r00t

First, let’s create the spring configuration file. In this configuration we will use the <util:properties> to load the properties configuration into Spring. And then we will use Spring EL to access the value of this properties and assign it to some bean’s properties.

<?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"
       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:properties id="database" location="classpath:database.properties"/>

    <bean id="dataSource" class="org.kodejava.example.spring.model.MyDataSource">
        <property name="driverClassName" value="#{database['jdbc.driverClassName']}"/>
        <property name="url" value="#{database['jdbc.url']}"/>
        <property name="username" value="#{database['jdbc.username']}"/>
        <property name="password" value="#{database['jdbc.password']}"/>
    </bean>
</beans>

To read a value from properties file what you do is the same as how we access an element of a map object. We pass the name of the properties as the key in the Spring EL.

<property name="driverClassName" value="#{database['jdbc.driverClassName']}"/>

The MyDataSource class is an imaginary data source object. It has some properties such as the driverClassName, url, username and password. It’s a common parameter you use to connect to a database using a JDBC driver. For simplicity the getters and setters we removed from the class.

package org.kodejava.example.spring.model;

public class MyDataSource {
    private String driverClassName;
    private String url;
    private String username;
    private String password;

    //
    // Getters & Setters
    //
}

As always, to run the Spring configuration above we will need to create a main class that load and execute the application context. This class will obtain the dataSource bean from the application context and print out its properties whose values are read from a properties file called database.properties.

package org.kodejava.example.spring;

import org.kodejava.example.spring.model.MyDataSource;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class SpELPropertiesExample {
    public static void main(String[] args) {
        ApplicationContext context =
                new ClassPathXmlApplicationContext("spel-properties.xml");

        MyDataSource dataSource = (MyDataSource) context.getBean("dataSource");
        System.out.println("driverClassName = " + dataSource.getDriverClassName());
        System.out.println("url             = " + dataSource.getUrl());
        System.out.println("username        = " + dataSource.getUsername());
        System.out.println("password        = " + dataSource.getPassword());
    }
}

Here are the result you get when running the code snippet:

driverClassName = com.mysql.jdbc.Driver
url             = jdbc:mysql://localhost/mydb
username        = root
password        = r00t

How do I access Map element using Spring EL?

In the previous example, How do I access collections members using Spring EL?, you have seen how to access a member of a collection using Spring EL square-braces [] operator. In this post you will learn how to use the same operator to access an element of a Map object.

For demonstration we will use the same Book class in the previous example to create the bean. The class without the corresponding getters and setters is as follow:

package org.kodejava.example.spring.model;

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

    //
    // Getters & Setters
    //
}

Next, let’s create the spring configuration file. In this configuration file we create a map using the <util:map> with the map id of books and add some key-value pair entries in the map.

<?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:map id="books">
        <entry key="0-201-61622-X" value="The Pragmatic Programmer"/>
        <entry key="978-1-934356-56-2" value="Hello, Android"/>
        <entry key="978-1-933988-69-6" value="Secret of The JavaScript Ninja"/>
        <entry key="978-1-449-37017-6" value="Java EE 7 Essentials"/>
        <entry key="9781935182962" value="Spring Roo in Action"/>
    </util:map>

    <bean id="book1" class="org.kodejava.example.spring.model.Book"
            p:title="#{books['9781935182962']}"/>
    <bean id="book2" class="org.kodejava.example.spring.model.Book"
            p:title="#{books['978-1-933988-69-6']}"/>
</beans>

After defining the map you can see how we access an element of the map. We use the square-braces operator [], we use the same operator as we are accessing a collection member. But instead of passing the index to the operator we pass the key of the map element that we are going to read.

<bean id="book2" class="org.kodejava.example.spring.model.Book"
            p:title="#{books['978-1-933988-69-6']}"/>

Finally to run the configuration you’ll need to create the following class:

package org.kodejava.example.spring;

import org.kodejava.example.spring.model.Book;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class SpELMapExample {
    public static void main(String[] args) {
        ApplicationContext context =
                new ClassPathXmlApplicationContext("spel-map.xml");

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

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

And example of output produced by this code can be seen below:

INFO: Loading XML bean definitions from class path resource [spel-map.xml]
book1.getTitle() = Spring Roo in Action
book2.getTitle() = Secret of The JavaScript Ninja

How do I access collections members using Spring EL?

In another posts about Spring EL examples you have learn the basic of 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.example.spring.model;

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.example.spring.model.Book"
                p:title="Essential C# 4.0" p:author="Michaelis"/>
        <bean class="org.kodejava.example.spring.model.Book"
              p:title="User Stories Applied" p:author="Mike Cohen"/>
        <bean class="org.kodejava.example.spring.model.Book"
              p:title="Learning Android" p:author="Marco Gargenta"/>
        <bean class="org.kodejava.example.spring.model.Book"
              p:title="The Ruby Programming Language"
              p:author="David Flanagan &amp; Yukihiro Matsumoto"/>
        <bean class="org.kodejava.example.spring.model.Book"
              p:title="Einstein" p:author="Walter Isaacson"/>
    </util:list>

    <bean id="book" class="org.kodejava.example.spring.model.Book">
        <property name="title" value="#{books[1].title}"/>
        <property name="author" value="#{books[1].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[1].title}"/>
<property name="author" value="#{books[1].author}"/>

Which can be read as: please give me the collection object at index number 1 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 User Stories Applied.

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.example.spring;

import org.kodejava.example.spring.model.Book;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class SpELCollectionExample {
    public static void main(String[] args) {
        ApplicationContext 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:

INFO: Loading XML bean definitions from class path resource [spel-collection.xml]
book.getTitle() = User Stories Applied
book.getAuthor() = Mike Cohen

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 is a 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.example.spring.model.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>
</beans>

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

package org.kodejava.example.spring.model;

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.example.spring;

import org.kodejava.example.spring.model.User;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class SpELRegexExample {
    public static void main(String[] args) {
        ApplicationContext 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());
    }
}

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

INFO: Loading XML bean definitions from class path resource [spel-regex.xml]
user.getEmail()     = [email protected]
user.isEmailValid() = true

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.example.spring.model.Book">
        <property name="type" value="Novel"/>
    </bean>
    <bean id="book2" class="org.kodejava.example.spring.model.Book">
        <property name="type" value="#{book1.type != null ? book1.type : 'Novel'}"/>
    </bean>
    <bean id="book3" class="org.kodejava.example.spring.model.Book">
        <property name="type" value="#{book1.type ?: 'Novel'}"/>
    </bean>
</beans>

In the configuration you’ll see that there are two way 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 duplication 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'. Which 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.example.spring.model;

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.example.spring;

import org.kodejava.example.spring.model.Book;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class SpELTernaryOperatorExample {
    public static void main(String[] args) {
        ApplicationContext 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.

INFO: Loading XML bean definitions from class path resource [spel-ternary.xml]
book1.getType() = Novel
book2.getType() = Novel
book3.getType() = Novel

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 a 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 MyGlass pojo.

package org.kodejava.example.spring.model;

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

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

    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.example.spring.model.MyGlass">
        <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.example.spring.model.MyGlass">
        <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.example.spring.spel;

import org.kodejava.example.spring.model.MyGlass;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class SpELLogicalExpression {
    public static void main(String[] args) {
        ApplicationContext context =
                new ClassPathXmlApplicationContext("spel-logical-expression.xml");
        MyGlass smallGlass = (MyGlass) context.getBean("smallGlass");
        MyGlass largeGlass = (MyGlass) 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:

INFO: Loading XML bean definitions from class path resource [spel-logical-expression.xml]
smallGlass.isLargeGlass() = false
largeGlass.isLargeGlass() = true