Spring Reading Property Files

Properties files are files which stores information about some external details like data base connection user and password details. The properties file should end with .properties extension. Lets have an example which takes values from properties file and displays here.

Jdbc.properties


jdbc.user = root
jdbc.password = letmein

Robot.java


//here we used spring annotations, @Component is used to specify to 
//which class we are injecting bean properties.
//@Autowired annotation is used to inject values
package com.sourceforopensource.pojos;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class Robot {

private String id = "Default robot";
private String speech = "hello";

public void speak() {
System.out.println(id + ": " + speech);
}

@Autowired
public void setId(@Value("${jdbc.user}") String id) {
this.id = id;
}

@Autowired
public void setSpeech(@Value("${jdbc.password}") String speech) {
this.speech = speech;
}
}

beans.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"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd">

<context:component-scan base-package="com.sourceforopensource.pojos">
</context:component-scan>


<context:property-placeholder
location="com/sourceforopensource/props/jdbc.properties" />

</beans>

App.java


package com.sourceforopensource.pojos;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class App {

public static void main(String[] args) {

ApplicationContext context = new ClassPathXmlApplicationContext("com/sourceforopensource/beans/beans.xml");

Robot robot = (Robot)context.getBean("robot");

robot.speak();

((ClassPathXmlApplicationContext)context).close();
}

}

output:

root: letmein

Balakrishna Pendyala

Author: Balakrishna Pendyala

Balakrishna is a Software Engineer working in Media Streaming Domain, and also worked on Banking and Health Care domains. His areas of interest include Object Oriented Design, SOLID Design principles, Restful Web Services and Open Source softwares including Spring, Spring Boot, and Hibernate.

If you found an error, highlight it and press Shift + Enter or click here to inform us.

Leave a Reply

Your email address will not be published. Required fields are marked *