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.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost/kodejava
jdbc.username=root
jdbc.password=secret

First, let’s create the spring configuration file. In this configuration we will use the <util:properties> to load the properties file into Spring. And then we will use Spring EL to access the value of these 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.spring.core.el.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.spring.core.el;

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.spring.core.el;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class SpELPropertiesExample {
    public static void main(String[] args) {
        try (ClassPathXmlApplicationContext 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.cj.jdbc.Driver
url             = jdbc:mysql://localhost/kodejava
username        = root
password        = secret

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

What are the system properties used for sending email?

Here are a list of system properties that can be used to send an e-mail using the JavaMail API.

Property Default Value Description
mail.host Define the host name of the mail server.
mail.smtp.host Define the host name of the SMTP server; this will overrides the mail.host for SMTP connections only.
mail._protocol_.host Define the host name of the specified protocol (POP, IMAP); this will overrides the mail.host.
mail.user Define the default username sent to all mail servers.
mail._protocol_.user Define the default username for the specified protocol; this will overrides the mail.user for the specified protocol.
mail.smtp.port 25 Define the SMTP port on which the SMTP server is listening.
mail._protocol_.port Default port for the corresponding protocol Define the port on which the servers for the specified protocol is listening.
mail.smtp.starttls.enable Upgrade the regular SMTP connection on the usual port to an encrypted (TLS or SSL) connection.
mail.smtp.connectiontimeout Infinite Define the number of milliseconds to wait for a connection timeout.
mail.debug false Define parameter for disabling or enabling information debugging.
mail.from Define the e-mail address to use in the From header.
mail.mime.charset file.encoding Define the default character set used to send messages.
mail.alternates Define other email address for the current that will not to be included when replying to a message.
mail._protocol_.class Define the fully package qualified class name of the provider for the specified protocol.
mail.transport.protocol First transport provider in the configuration file Define default protocol with which to send messages.
mail.transport.protocol.address-type Define the message transport protocol such as SMTP for the specified address type, for example mail.transport.protocol.rfc822.
mail.replayallcc false Put all recipients in the CC list of the reply message instead of the TO field when replying to all.

How to establish connection to a database using Properties object?

In the following code snippet, you will see how to pass some connection arguments when connecting to a database. To do this, we can use the java.util.Properties class. We can put some key value pairs as a connection arguments to the Properties object
before we pass this information into the DriverManager class.

Let’s see the example below:

package org.kodejava.jdbc;

import java.sql.*;
import java.util.Properties;

public class GetConnectionWithProperties {
    private static final String URL = "jdbc:mysql://localhost/kodejava";
    private static final String USERNAME = "kodejava";
    private static final String PASSWORD = "s3cr*t";

    public static void main(String[] args) {
        GetConnectionWithProperties demo = new GetConnectionWithProperties();
        try (Connection connection = demo.getConnection()) {
            // do something with the connection.
            Statement stmt = connection.createStatement();
            ResultSet rs = stmt.executeQuery("SELECT * FROM product");
            while (rs.next()) {
                System.out.println("Code = " + rs.getString("code"));
                System.out.println("Name = " + rs.getString("name"));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    private Connection getConnection() throws SQLException {
        Properties connectionProps = new Properties();
        connectionProps.put("user", USERNAME);
        connectionProps.put("password", PASSWORD);

        Connection connection = DriverManager.getConnection(URL, connectionProps);
        System.out.println("Connected to database.");
        return connection;
    }
}

Maven Dependencies

<dependency>
    <groupId>com.mysql</groupId>
    <artifactId>mysql-connector-j</artifactId>
    <version>8.4.0</version>
</dependency>

Maven Central

How do I inject collections using props element in Spring?

This time we will demonstrate how to inject a java.util.Properties. This class store a key-value pairs of data where the key and the values are both in string. You can use the <props> element to wire a property collections.

The bean we use in this example is taken from the previous example How do I inject collections using list element in Spring?.

Let’s create the configuration file and call it collection-props.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="song1" class="org.kodejava.spring.core.Song">
        <property name="title" value="I Saw Her Standing There" />
        <property name="writer" value="Beatles" />
    </bean>

    <bean id="song2" class="org.kodejava.spring.core.Song">
        <property name="title" value="Misery" />
        <property name="writer" value="Beatles" />
    </bean>

    <bean id="song3" class="org.kodejava.spring.core.Song">
        <property name="title" value="Anna (Go to Him)" />
        <property name="writer" value="Beatles" />
    </bean>

    <bean id="publisher" class="org.kodejava.spring.core.Publisher">
        <property name="name" value="EMI Studios" />
    </bean>

    <bean id="album" class="org.kodejava.spring.core.Album">
        <property name="title" value="Please Please Me" />
        <property name="year" value="1963" />
        <property name="props">
            <props>
                <prop key="color">Black</prop>
                <prop key="type">CD</prop>
                <prop key="duration">1 Hour</prop>
            </props>
        </property>
    </bean>

</beans>

To wire property collections we use the <props> element. This element can have many <prop> in it. The key of the property defined by the key attribute of this element. The value of the property is set in the body of this element.

As usual let’s create a simple program to run it:

package org.kodejava.spring.core;

import org.springframework.context.support.ClassPathXmlApplicationContext;

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

            Album album = (Album) context.getBean("album");
            System.out.println("Album = " + album);
        }
    }
}

When you run it, it will produce the following output:

Album = Album{title='Please Please Me', year=1963, songs=[], publisher={}, props={color=Black, type=CD, duration=1 Hour}}

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 convert Properties into Map?

package org.kodejava.util;

import java.util.Properties;
import java.util.Map;
import java.util.HashMap;
import java.util.Set;

public class PropertiesToMap {
    public static void main(String[] args) {
        // Create a new instance of Properties.
        Properties properties = new Properties();

        // Populate properties with a dummy application information
        properties.setProperty("app.name", "HTML Designer");
        properties.setProperty("app.version", "1.0");
        properties.setProperty("app.vendor", "HTML Designer Inc");

        // Create a new HashMap and pass an instance of Properties. Properties
        // is an implementation of a Map which keys and values stored as in a
        // String.
        Map<Object, Object> map = new HashMap<>(properties);

        // Get the entry set of the Map and print it out.
        Set<Map.Entry<Object, Object>> propertySet = map.entrySet();
        for (Map.Entry<Object, Object> entry : propertySet) {
            System.out.printf("%s = %s%n", entry.getKey(), entry.getValue());
        }
    }
}

The output of the code snippet above:

app.vendor = HTML Designer Inc
app.name = HTML Designer
app.version = 1.0