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