how to access properties file in Spring


PropertyPlaceHolderConfigurer A property resource configurer that resolves placeholders in bean property values of context definitions. It pulls values from a properties file into bean definitions.

The default placeholder syntax follows the Ant / Log4J / JSP EL style: ‘$’

PropertyOverrideConfigurer A property resource configurer that overrides bean property values in an application context definition. It pushes values from a properties file into bean definitions
Example:
A simple class of which values are set from property file.

public class MyBean {

private String myName;
private String password;
/**
* @param args
*/
public static void main(String[] args) {

ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("mybean.xml");
MyBean bean = (MyBean)ctx.getBean("myBean");
// getting the properties from the property file
System.out.println(bean.getMyName());
System.out.println(bean.getPassword());
}
public String getMyName() {
return myName;
}
public void setMyName(String myName) {
this.myName = myName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}

}

The xml file config

<?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-2.5.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd"
default-lazy-init="true">

<bean id="configProperties"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>config.properties</value>
</list>
</property>
</bean>

<bean id="myBean" class="test.tetst.MyBean">
<property name="myName" value="${myname}" />
<property name="password" value="${password}" />
</bean>
</beans>

config.properties files
myname=testing
password=password

3 thoughts on “how to access properties file in Spring

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s