Inheriting Bean in Spring

By utilizing the guardian property of bean, we can indicate the legacy connection between the beans. In such case, guardian bean qualities will be acquired to the present bean. Now about we see the basic case to inheriting the bean folder. holds, This class contains three properties, three constructor and show() technique to show the qualities.

Let's see the simple example to inherit the bean.

This class contains three properties, three constructor and show() method to display the values.

package com.javatportal;

public class Employee {
private int id;
private String name;
private Address address;
public Employee() {}

public Employee(int id, String name) {
	super(); = id; = name;
public Employee(int id, String name, Address address) {
	super(); = id; = name;
	this.address = address;

void show(){
	System.out.println(id+" "+name);

package com.javatportal;

public class Address {
private String addressLine1,city,state,country;

public Address(String addressLine1, String city, String state, String country) {
	this.addressLine1 = addressLine1; = city;
	this.state = state; = country;
public String toString(){
	return addressLine1+" "+city+" "+state+" "+country;


<?xml version="1.0" encoding="UTF-8"?>

<bean id="e1" class="com.javatportal.Employee">
<constructor-arg value="101"></constructor-arg>
<constructor-arg  value="Sachin"></constructor-arg>

<bean id="address1" class="com.javatportal.Address">
<constructor-arg value="21,Lohianagar"></constructor-arg>
<constructor-arg value="Ghaziabad"></constructor-arg>
<constructor-arg value="UP"></constructor-arg>
<constructor-arg value="USA"></constructor-arg>

<bean id="e2" class="com.javatportal.Employee" parent="e1">
<constructor-arg ref="address1"></constructor-arg>


This class gets the bean from the applicationContext.xml file and calls the show method.

package com.javatportal;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;

public class Test {
public static void main(String[] args) {
	Resource r=new ClassPathResource("applicationContext.xml");
	BeanFactory factory=new XmlBeanFactory(r);
	Employee e1=(Employee)factory.getBean("e2");;

In this post, you will learn:
  1. What is Inheriting Bean in Spring ?