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

Share:

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:

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.

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.

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.

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.

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

  • Adrian

    Hi, i have a problem with util:properties , error ( The prefix “util” for element “util:properties” is not bound ). Thanks !

    • Wayan Saryada

      Hi Adrian,

      Have you correctly define the namespace and the schema location for the util element in your Spring configuration file?

  • Anibal Gomez

    For setting a propertie value is the same way?