Load properties file in spring application context - Java @ Desk

Tuesday, July 2, 2013

Load properties file in spring application context

There are two ways to load a property file in spring configuration xml file.

1) Using org.springframework.beans.factory.config.PropertyPlaceholderConfigurer class
2) Using tag <context:property-placeholder/>

1) Using org.springframework.beans.factory.config.PropertyPlaceholderConfigurer class

spring-config.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:context="http://www.springframework.org/schema/context"  
 xmlns:p="http://www.springframework.org/schema/p"  
 xsi:schemaLocation="  
 http://www.springframework.org/schema/beans  
 http://www.springframework.org/schema/beans/spring-beans-3.0.xsd  
 http://www.springframework.org/schema/context  
 http://www.springframework.org/schema/context/spring-context-3.0.xsd">  
      <bean id="props" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">  
           <property name="locations" value="classpath:com/eclipse/e3.properties" />  
      </bean>  
      <bean id="xyz" class="CLASS_NAME">  
       <property name="domainName" value="${domainName}"/>  
       <property name="instanceName" value="${instanceName}"/>  
      </bean>  
 </beans>  
e3.properties
 domainName=rulesdomain  
 instanceName=DOC_DEV  
2) Using tag <context:property-placeholder/>
 <?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:context="http://www.springframework.org/schema/context"  
 xmlns:p="http://www.springframework.org/schema/p"  
 xsi:schemaLocation="  
 http://www.springframework.org/schema/beans  
 http://www.springframework.org/schema/beans/spring-beans-3.0.xsd  
 http://www.springframework.org/schema/context  
 http://www.springframework.org/schema/context/spring-context-3.0.xsd">  
      <context:property-placeholder location="classpath:com/eclipse/e3.properties" />  
      <bean id="xyz" class="CLASS_NAME">  
       <property name="domainName" value="${domainName}"/>  
       <property name="instanceName" value="${instanceName}"/>  
      </bean>  
 </beans>  
At runtime, ${domainName} value will be replaced with the value from e3.properties file.






No comments:

Post a Comment