Wednesday, 18 December 2013

Reading properties file in Spring

weekendplan_prod.properties
activation.user.notvalid.msg  = Requested user is not authorized.
 
applicationContext.xml
 
<bean id="kleverlinksProperties" 
class="com.kleverlinks.common.utils.KleverlinksPropertyutil"> <property name="systemPropertiesModeName" 
value="SYSTEM_PROPERTIES_MODE_OVERRIDE"/>
          <property name="ignoreResourceNotFound" value="true"/>
          <property name="locations">
            <list>
              <value>classpath:weekendplan_prod.properties</value>
            </list>
          </property>
          <property name="ignoreUnresolvablePlaceholders" value="true"/>
        </bean>
weekendplan_prod.properties is name of the property file.
 
KleverlinksPropertyutil.java
package com.kleverlinks.common.utils;
import java.io.IOException;
import java.util.Properties;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;

/**
 * 
 * Loads properties from the property file.
 * 
 */
public class KleverlinksPropertyutil extends PropertyPlaceholderConfigurer{
  private static Log log = LogFactory.getLog(KleverlinksPropertyutil.class);
  static Properties proeprties;
  public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory)
  throws BeansException
   {
       try
       {
        proeprties = mergeProperties();
        convertProperties(proeprties);
        processProperties(beanFactory, proeprties);
       }
       catch(IOException ex)
       {
        log.error("Exception while reading the properties file " +ex);
       }
    }
     public static String getStringValue(String key) {
      return proeprties.getProperty(key);
     }

}
How to use properties in property file
System.out.println( KleverlinksPropertyutil.getStringValue("activation.user.notvalid.msg"));  
OUTPUT:
Requested user is not authorized.
Another way to configure property file:
<bean
    class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
     <property name="location">
      <value>database.properties</value>
    </property>
  </bean>
 
 
 

No comments: