Loading Property values in Spring MVC

In any software application ,we are required to put certain configurable properties in the property file
And access those values in the application wherever needed.

This enables to change the property values as and when they want without changing the code.

To enable the Spring to load the properties from the property file , we need to register the below bean in spring context

  1. <bean id="dbProperties"
  2.     class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
  3.  
  4.     <property name="location" value="classpath:db.properties" />
  5.  
  6. </bean>
<bean id="dbProperties"
    class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
 
    <property name="location" value="classpath:db.properties" />
 
</bean>


Loading property values in spring xml file by using placeholder resolver

In this approach , we will see how to load properties from properties file and access them in the spring xml file.

Assume that , we are creating a bean for Data Source which will have DB related properties.

We will keep them in the db.properties file as below

db.properties

  1. driverClassName = com.mysql.jdbc.Driver
  2. url = jdbc:mysql://localhost:3306/userDB
  3. username = kb
  4. password = 1234
driverClassName = com.mysql.jdbc.Driver
url = jdbc:mysql://localhost:3306/userDB
username = kb
password = 1234


To access these property files in xml file, we use placeholder resolver as below

  1. <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
  2.     <property name="driverClassName" value="${ driverClassName}" />
  3.     <property name="url" value="${url}" />
  4.     <property name="username" value="${username}" />
  5.     <property name="password" value="${password}" />
  6. </bean>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="${ driverClassName}" />
    <property name="url" value="${url}" />
    <property name="username" value="${username}" />
    <property name="password" value="${password}" />
</bean>

Spring will replace these placeholders like ${xxx} with the property values from the property file.

Loading property values in Java file using @Value annotation

Using @Value annotation, we can load the values from the property file in the Java file as below

  1. @Controller
  2. public class HelloController {
  3.  
  4. @Value(“${message})
  5. Private String message;
  6.    
  7.    
  8.     @RequestMapping(value="/hello",method=RequestMethod.GET)
  9.     public String displayHelloPage(Model model){
  10.        
  11.  
  12.         model.addAttribute("message", message);
  13.         return "/hello";
  14.     }
  15.  
  16. }
@Controller
public class HelloController {

@Value(“${message}”)
Private String message;
	
	
	@RequestMapping(value="/hello",method=RequestMethod.GET)
	public String displayHelloPage(Model model){
		

		model.addAttribute("message", message);
		return "/hello";
	}

}

Lets create the project

Project structure

db.properties

  1. driverClassName = com.mysql.jdbc.Driver
  2. url = jdbc:mysql://localhost:3306/userDB
  3. username = kb
  4. password = 1234
driverClassName = com.mysql.jdbc.Driver
url = jdbc:mysql://localhost:3306/userDB
username = kb
password = 1234


create the application.properties

  1. dateFormat=dd/MM/yyyy
dateFormat=dd/MM/yyyy


create the spring configuration file

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
  4.     xmlns:context="http://www.springframework.org/schema/context"
  5.     xmlns:mvc="http://www.springframework.org/schema/mvc"
  6.     xsi:schemaLocation="http://www.springframework.org/schema/beans
  7.        http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
  8.        http://www.springframework.org/schema/context
  9.        http://www.springframework.org/schema/context/spring-context-3.2.xsd
  10.        http://www.springframework.org/schema/mvc
  11.        http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">
  12.  
  13.     <context:component-scan base-package="com.kb" />
  14.     <mvc:annotation-driven />
  15.  
  16.     <bean id="viewResolver"
  17.         class="org.springframework.web.servlet.view.InternalResourceViewResolver">
  18.         <property name="prefix" value="/WEB-INF/pages/" />
  19.         <property name="suffix" value=".jsp" />
  20.     </bean>
  21.  
  22. <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
  23.     <property name="driverClassName" value="${driverClassName}" />
  24.     <property name="url" value="${url}" />
  25.     <property name="username" value="${username}" />
  26.     <property name="password" value="${password}" />
  27. </bean>
  28.  
  29. <bean id="dbProperties"
  30.     class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
  31.     <property name="locations">
  32.     <list>
  33.     <value>classpath:db.properties</value>
  34.     <value>classpath:application.properties</value>
  35.     </list>
  36.     </property>
  37. </bean>
  38. </beans>
<?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:context="http://www.springframework.org/schema/context"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.2.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">

	<context:component-scan base-package="com.kb" />
	<mvc:annotation-driven />

	<bean id="viewResolver"
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/WEB-INF/pages/" />
		<property name="suffix" value=".jsp" />
	</bean>

<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="${driverClassName}" />
    <property name="url" value="${url}" />
    <property name="username" value="${username}" />
    <property name="password" value="${password}" />
</bean>

<bean id="dbProperties"
    class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="locations">
    <list>
    <value>classpath:db.properties</value>
    <value>classpath:application.properties</value>
    </list>
    </property>
</bean>
</beans>


We have defined 2 properties files and loading them using spring property loaded bean PropertyPlaceHolderConfigurer.

All the values referred using ${xxx} in the above xml are loaded using PropertyPlaceholderConfigurer from the properties file.

HomeController.java

  1. package com.kb;
  2.  
  3. import org.springframework.beans.factory.annotation.Value;
  4. import org.springframework.stereotype.Controller;
  5. import org.springframework.ui.Model;
  6. import org.springframework.web.bind.annotation.RequestMapping;
  7. import org.springframework.web.bind.annotation.RequestMethod;
  8.  
  9. @Controller
  10. public class HomeController {
  11.    
  12.     @Value("${dateFormat}")
  13.     String dateFormat;
  14.    
  15.     @RequestMapping(value="/home",method=RequestMethod.GET)
  16.     public String getHomePage(Model model){
  17.         model.addAttribute("dateFormat", dateFormat);
  18.         return "/home";
  19.        
  20.     }
  21.  
  22. }
package com.kb;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
public class HomeController {
	
	@Value("${dateFormat}")
	String dateFormat;
	
	@RequestMapping(value="/home",method=RequestMethod.GET)
	public String getHomePage(Model model){
		model.addAttribute("dateFormat", dateFormat);
		return "/home";
		
	}

}


We are using @Value annotation to load the property value from the properties file.
We have passed key as an attribute for @Value annotation.

create the home.jsp

  1. <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
  2.     pageEncoding="ISO-8859-1"%>
  3. <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
  4. <%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>
  5. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
  6. <html>
  7. <head>
  8. <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
  9. <title>Home</title>
  10. </head>
  11. <body>
  12.  <div align="center">
  13.         <h2>Date format is ${dateFormat}</h2>
  14.   </div>
  15. </body>
  16. </html>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Home</title>
</head>
<body>
 <div align="center">
        <h2>Date format is ${dateFormat}</h2>
  </div>
</body>
</html>


In this page, we are getting the value for dateFormat added in the model attribute.

create pom.xml

  1. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  2.   xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  3.   <modelVersion>4.0.0</modelVersion>
  4.   <groupId>Spring</groupId>
  5.   <artifactId>PropertiesLoading</artifactId>
  6.   <packaging>war</packaging>
  7.   <version>0.0.1-SNAPSHOT</version>
  8.   <name>PropertiesLoading Maven Webapp</name>
  9.   <url>http://maven.apache.org</url>
  10.     <properties>
  11.         <org.springframework.version>4.2.0.RELEASE</org.springframework.version>
  12.     </properties>
  13.   <dependencies>
  14.     <dependency>
  15.       <groupId>junit</groupId>
  16.       <artifactId>junit</artifactId>
  17.       <version>3.8.1</version>
  18.       <scope>test</scope>
  19.     </dependency>
  20.     <dependency>
  21.             <groupId>org.springframework</groupId>
  22.             <artifactId>spring-web</artifactId>
  23.             <version>${org.springframework.version}</version>
  24.         </dependency>
  25.  
  26.         <dependency>
  27.             <groupId>org.springframework</groupId>
  28.             <artifactId>spring-webmvc</artifactId>
  29.             <version>${org.springframework.version}</version>
  30.         </dependency>
  31.         <dependency>
  32.             <groupId>javax.servlet</groupId>
  33.             <artifactId>servlet-api</artifactId>
  34.             <version>2.5</version>
  35.             <scope>provided</scope>
  36.         </dependency>
  37.         <dependency>
  38.     <groupId>javax.servlet.jsp.jstl</groupId>
  39.     <artifactId>javax.servlet.jsp.jstl-api</artifactId>
  40.     <version>1.2.1</version>
  41. </dependency>
  42. <dependency>
  43.     <groupId>taglibs</groupId>
  44.     <artifactId>standard</artifactId>
  45.     <version>1.1.2</version>
  46. </dependency>
  47. <dependency>
  48.     <groupId>org.springframework</groupId>
  49.     <artifactId>spring-jdbc</artifactId>
  50.     <version>3.0.4.RELEASE</version>
  51. </dependency>
  52. <dependency>
  53.         <groupId>mysql</groupId>
  54.         <artifactId>mysql-connector-java</artifactId>
  55.         <version>5.1.9</version>
  56.     </dependency>
  57.  
  58.   </dependencies>
  59.   <build>
  60.     <finalName>PropertiesLoading</finalName>
  61.     <plugins>
  62.             <plugin>
  63.                 <groupId>org.apache.maven.plugins</groupId>
  64.                 <artifactId>maven-compiler-plugin</artifactId>
  65.                 <version>2.5.1</version>
  66.                 <configuration>
  67.                     <source>1.8</source>
  68.                     <target>1.8</target>
  69.                 </configuration>
  70.             </plugin>
  71.         </plugins>
  72.   </build>
  73. </project>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>Spring</groupId>
  <artifactId>PropertiesLoading</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>PropertiesLoading Maven Webapp</name>
  <url>http://maven.apache.org</url>
    <properties>
		<org.springframework.version>4.2.0.RELEASE</org.springframework.version>
	</properties>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
    <dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-web</artifactId>
			<version>${org.springframework.version}</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>${org.springframework.version}</version>
		</dependency>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>servlet-api</artifactId>
			<version>2.5</version>
			<scope>provided</scope>
		</dependency>
		<dependency>
	<groupId>javax.servlet.jsp.jstl</groupId>
	<artifactId>javax.servlet.jsp.jstl-api</artifactId>
	<version>1.2.1</version>
</dependency>
<dependency>
	<groupId>taglibs</groupId>
	<artifactId>standard</artifactId>
	<version>1.1.2</version>
</dependency>
<dependency>
	<groupId>org.springframework</groupId>
	<artifactId>spring-jdbc</artifactId>
	<version>3.0.4.RELEASE</version>
</dependency>
<dependency>
		<groupId>mysql</groupId>
		<artifactId>mysql-connector-java</artifactId>
		<version>5.1.9</version>
	</dependency>

  </dependencies>
  <build>
    <finalName>PropertiesLoading</finalName>
    <plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>2.5.1</version>
				<configuration>
					<source>1.8</source>
					<target>1.8</target>
				</configuration>
			</plugin>
		</plugins>
  </build>
</project>


create web.xml

  1. <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  2.     xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
  3.     version="3.1">
  4.  
  5.     <display-name>PropertiesLoading</display-name>
  6.  
  7.     <!-- Spring MVC dispatcher servlet -->
  8.     <servlet>
  9.         <servlet-name>mvc-dispatcher</servlet-name>
  10.         <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  11.         <init-param>
  12.             <param-name>contextConfigLocation</param-name>
  13.             <param-value>
  14.             /WEB-INF/spring-mvc.xml,
  15.         </param-value>
  16.         </init-param>
  17.         <load-on-startup>1</load-on-startup>
  18.     </servlet>
  19.     <servlet-mapping>
  20.         <servlet-name>mvc-dispatcher</servlet-name>
  21.         <url-pattern>/</url-pattern>
  22.     </servlet-mapping>
  23.  
  24.     <listener>
  25.         <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  26.     </listener>
  27.  
  28. </web-app>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
	version="3.1">

	<display-name>PropertiesLoading</display-name>

	<!-- Spring MVC dispatcher servlet -->
	<servlet>
		<servlet-name>mvc-dispatcher</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>
			/WEB-INF/spring-mvc.xml,
		</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>
	<servlet-mapping>
		<servlet-name>mvc-dispatcher</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>

	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>

</web-app>


access below url

http://localhost:8080/PropertiesLoading/home

The value is getting picked up from the properties file.
Above value is defined inside application.properties.

Location of the property file

In Spring MVC application, we generally keep the properties file inside WEB-INF directory.

So if we want to load the property file from this location, we should define the location as below

  1. <property name="location" value="WEB-INF/application.properties"/>
<property name="location" value="WEB-INF/application.properties"/>

If we want to load the property file from the absolute path of the file, we can do that by defining location as below

  1. <property name="location" value="file:///D:/Config/application.properties" />
<property name="location" value="file:///D:/Config/application.properties" />

or

  1. <property name="location" value="file:D:/Config/application.properties" />
<property name="location" value="file:D:/Config/application.properties" />


Ignoring Exception thrown when resource and property key not found

By default, Spring will throw an exception if it could not find a properties file in the specified path or could not resolve a placeholder specified in the java file or xml file.
This leads to the application fails to start.

To ignore such exceptions thrown by Spring,we need to add the below additional properties to the PropertyPlaceholderConfigurer bean

  1. <property name="ignoreResourceNotFound" value="true" />
<property name="ignoreResourceNotFound" value="true" />

The above property signals Spring to ignore the exception when there is no property file available in the path specified.

  1. <property name="ignoreUnresolvablePlaceholders" value="true" />
<property name="ignoreUnresolvablePlaceholders" value="true" />

The above property signals Spring to ignore the exception when there is no placeholder available in the specified java or xml file.

The whole PropertyPlaceholderConfigurer bean should look like below

  1. <bean id="applicationProperties"  class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
  2.  
  3.     <property name="location" value="classpath:mail.properties" />
  4.     <property name="ignoreResourceNotFound" value="true" />
  5.     <property name="ignoreUnresolvablePlaceholders" value="true" />
  6.  
  7. </bean>
<bean id="applicationProperties"  class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
 
    <property name="location" value="classpath:mail.properties" />
    <property name="ignoreResourceNotFound" value="true" />
    <property name="ignoreUnresolvablePlaceholders" value="true" />
 
</bean>


Note:
When the property ignoreUnresolvablePlaceholders is set to true and a placeholder could not be resolved,Spring will inject name of the placeholder itself.

Download this project PropertiesLoading.zip

About the Author

Founder of javainsimpleway.com
I love Java and open source technologies and very much passionate about software development.
I like to share my knowledge with others especially on technology 🙂
I have given all the examples as simple as possible to understand for the beginners.
All the code posted on my blog is developed,compiled and tested in my development environment.
If you find any mistakes or bugs, Please drop an email to kb.knowledge.sharing@gmail.com

Connect with me on Facebook for more updates

Share this article on