Search This Blog

Saturday 11 August 2012

Using Spring's property-placeholder

With Spring it becomes necessary to configure our beans. This at times involves setting sensitive information in our XML files. In case of database connectivity it would be a username or password. People are not comfortable with this kind of details being available in their war files.
So in such cases sometimes JNDI is used. There is also the option of using encrypted property files. At times the data may not be sensitive, but changing it will require getting into archives and modifying XML files. An alternative is to maintain the data in property files. The values in the configuration get loaded at run time from the property files.
For our testing I created a simple property file:
name= Rajat Singh
age =20
The XML configuration is as below:
<context:annotation-config/>
<context:property-placeholder location="classpath:name.properties" />
    
<bean name="user" class="com.test.User">
    <property name="name" value="${name}"/>
    <property name="age" value="${age}"/>
</bean>
I executed the code to test the same:
public class TestClient {
    public static void main(String[] args) {
        final ApplicationContext applicationContext = new ClassPathXmlApplicationContext(
                "spring-properties.xml");
        User user = (User) applicationContext.getBean("user"); 
        System.out.println(user.getName() + " is " + user.getAge()+ " years old.");
        }
}

The start up logs indicate that Spring loaded the property files:
Apr 12, 2012 2:28:52 PM org.springframework.core.io.support.PropertiesLoaderSupport loadProperties
INFO: Loading properties file from class path resource [name.properties]
The output is as below:
Rajat Singh is 20 years old.
As can be seen the values were loaded from the property file and assigned to user's properties.
Here we have managed to move the configuration of bean properties to external poperty files. But what if we are using Spring annotations ? Can we get our property file values available in our java class ?

2 comments:

  1. I am trying to supply a runtime name of the file (my message queue.properties file differs for my different environment)







    But I am not able to set the $(hostname} with the name of my hostname for spring application context to load it dynamically.

    If you have pointers for the same that would be really helpful

    ReplyDelete
    Replies
    1. I am not sure I have understood the question. If you could provide me with some more details...

      Delete