Share on Google+Share on Google+

Spring Override Bean

In this tutorial you will see an example of overriding in spring framework.

Spring Override Bean

The support of inheritance is present in the Spring framework and common values or configuration is shared among beans. The child bean inherits the properties and configuration of the parent bean or base bean. The child class also override the inherited value.

package bean.configuration.inheritance;

public class Teacher {
	private Student student;
	private String teachername;
	private String subject;

	public String getSubject() {
		return subject;

	public void setSubject(String subject) {
		this.subject = subject;

	public Student getStudent() {
		return student;

	public void setStudent(Student student) {
		this.student = student;

	public String getTeachername() {
		return teachername;

	public void setTeachername(String teachername) {
		this.teachername = teachername;

	public String toString() {
		return "Teacher [Teacher Name=" + teachername + " Subject= " + subject
				+ ", Student=" + student + "]";


package bean.configuration.inheritance;

public class Student {
	private String name;
	private String address;

	public String getName() {
		return name;

	public void setName(String name) { = name;

	public String getAddress() {
		return address;

	public void setAddress(String address) {
		this.address = address;

	public String toString() {
		return "Student [Student Name=" + name + "Address=" + address + "]";

package bean.configuration.inheritance;

import org.springframework.context.ApplicationContext;

public class AppMain {
	public static void main(String[] args) {
		ApplicationContext context = new ClassPathXmlApplicationContext(
				new String[] { "context.xml" });
		Teacher cust = (Teacher) context.getBean("TeacherBean");


<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns=""
  xmlns:xsi="" xmlns:aop=""

  <bean id="baseBean" class="bean.configuration.inheritance.Teacher">
    <property name="subject" value="Science" />

  <bean id="TeacherBean" parent="baseBean">
     <property name="subject" value="Biology" /> 

    <property name="student" ref="StudentBean" />
    <property name="teachername" value="Rakesh" />


  <bean id="StudentBean" class="bean.configuration.inheritance.Student">
    <property name="name" value="satya" />
    <property name="address" value="delhi" />


When you run this application it will display message as shown below:

Teacher [Teacher Name=Rakesh Subject= Biology, Student=Student [Student Name=satyaAddress=delhi]]

Download this example code


Posted on: August 31, 2010 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.