Spring Bean Definition Inheritance

Spring supports bean configuration inheritance.Normally A bean definition can contain a lot of configuration information, including constructor arguments, property values, and container-specific information such as initialization method, static factory method name.

A child bean definition inherits configuration data from a parent bean definition.

The child definition can override the inherited values.

by using spring Bean Inheritance we can define a bean and configure in spring configuration file to create new bean.

Lets See An Example For Spring Bean Definition Inheritance

The Project Structure



Person.java


package com.javalschool;
public class Person {
private String personId;
private String personName;
private String Address;
public String getPersonId() {
return personId;
}
public void setPersonId(String personId) {
this.personId = personId;
}
public String getPersonName() {
return personName;
}
public void setPersonName(String personName) {
this.personName = personName;
}
public String getAddress() {
return Address;
}
public void setAddress(String address) {
Address = address;
}
@Override
public String toString() {
return "Person [personId=" + personId + ", personName=" + personName
+ ", Address=" + Address + "]";
}


}

Spring Configuration file applicationContext.xml


<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
"http://www.springframework.org/dtd/spring-beans.dtd">
>beans>
>bean id = "personBean" class = "com.javalschool.Person" abstract = "true">
>property name = "address" value = "Bangalore">>/property>
>/bean>
>bean id = "childBean" parent = "personBean">
>property name = "personId" value= "12345"/>
>property name = "personName" value = "AAAAAA"/>
>/bean>
>/beans>

In Above "personBean" is parent bean and "childBean" is known as child bean and inheriting property is "address" and adding new properties are "personId" and "personName".in above spring container is creating "childBean(child bean)" by defining "personBean(parent bean)" in Spring cofiguration file.

Create a Test class and Run it(Test.java)


package com.javalschool;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Test {

public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
Person person = (Person)context.getBean("childBean");
System.out.println(person.toString());

}

}


output:


log4j:WARN No appenders could be found for logger (org.springframework.core.env.StandardEnvironment).
log4j:WARN Please initialize the log4j system properly.
Person [personId=12345, personName=AAAAAA, Address=Bangalore]


No comments:

Post a Comment