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


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;
public String toString() {
return "Person [personId=" + personId + ", personName=" + personName
+ ", Address=" + Address + "]";


Spring Configuration file applicationContext.xml

>bean id = "personBean" class = "com.javalschool.Person" abstract = "true">
>property name = "address" value = "Bangalore">>/property>
>bean id = "childBean" parent = "personBean">
>property name = "personId" value= "12345"/>
>property name = "personName" value = "AAAAAA"/>

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");




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