Wednesday, April 24, 2013

How to define a property file in spring context and how to retrieve data from the property file

It is always a good practise to use property file to store configuration data kind of things.First we have to define it in the spring context  as below.lets take our property file as test.properties.
 
<bean id="propertyConfigurer"  class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations" value="classpath : test.properties"/>
</bean>
 
 As we are going to use java.util.Properties we have to define PropertiesFactoryBean as a bean in our context file as below.
 
<bean id="properties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<property name="location" value="classpath : test.properties"/>
 </bean>
 
Also we will use @Autowired annotation when retrieving data.So lets define the below in our context file as well.

 
<context:annotation-config />  Now we have completed the spring context side changes.Lets see how to reach data.  public class Test{

@Autowired
private Properties properties;

private void test(){

String value=properties.getProperty("key");

}




Hope this helps .