Home  >  Spring Core

Example of PropertyOverrideConfigurer in Spring (context:property-override)

By Arvind Rai, April 23, 2013
PropertyOverrideConfigurer can override the bean values fetching from property file in spring application context. To achieve it we use PropertyOverrideConfigurer class as follows.
<bean class="org.springframework.beans.factory.config.PropertyOverrideConfigurer">
	<property name="location" value="classpath:beanOverride.cfg" />
</bean>  
We can achieve the same using <context:property-override> as follows.
<context:property-override location="classpath:beanOverride.cfg"/>
 
We need to configure properties file in the format
beanName.property=value
We will understand by example.
app-conf.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"
       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 class="org.springframework.beans.factory.config.PropertyOverrideConfigurer">
	<property name="location" value="classpath:beanOverride.cfg" />
    </bean> 
    <bean id="person" class="com.concretepage.Person" >
       <property name="name" value="Ram"/>
       <property name="age" value="20"/>
       <property name="location" value="Varanasi"/>
    </bean> 
</beans> 

beanOverride.cfg
person.age=40
person.location=Delhi 

Person.java
package com.concretepage;
public class Person {
	private String name;
	private int age;
	private String location;
		
	public String getLocation() {
		return location;
	}
	public void setLocation(String location) {
		this.location = location;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
} 

SpringAppTest.java
package com.concretepage;
import java.sql.SQLException;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class SpringAppTest {
	public static void main(String[] args) throws SQLException {
		AbstractApplicationContext  context = new ClassPathXmlApplicationContext("app-conf.xml");
		Person person=(Person)context.getBean("person");
		System.out.println(person.getName());
		System.out.println(person.getAge());
		System.out.println(person.getLocation());
		context.registerShutdownHook();
	}
}  

Output
Ram
40
Delhi 

Download Source Code

POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS


©2019 concretepage.com | Privacy Policy | Contact Us