Spring PropertyOverrideConfigurer (context:property-override)

By Arvind Rai, November 01, 2021
Spring PropertyOverrideConfigurer is used to override the bean values fetching from property file in Spring application context.
Find the code to use PropertyOverrideConfigurer class.
<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 in property file in below format.
beanName.property=value 

Using PropertyOverrideConfigurer

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.xsd
           http://www.springframework.org/schema/context
           http://www.springframework.org/schema/context/spring-context.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 

Reference

Class PropertyOverrideConfigurer

Download Source Code

POSTED BY
ARVIND RAI
ARVIND RAI
LEARN MORE








©2024 concretepage.com | Privacy Policy | Contact Us