Spring bean inheritance

  • Facebook
  • Google
  • LinkedIn
  • Twitter

You know the benefit of inheritance in java which is Reusability. Means if you have some properties in the base class then child class will inherit those properties and its values and also you can override those values in the Child class.

Similar concept of inheritance is provided in Spring where bean definition is inherited in other bean

A bean can contain a lot of configuration information means like including constructor arguments, property values, and other container-specific information such as static factory method name, initialization method and so on. A child bean inherits these configuration data from a parent definition.

Create maven project and add the dependency in the POM file.
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>Spring</groupId>
	<artifactId>SpringCore</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>

	<name>SpringCore</name>
	<url>http://maven.apache.org</url>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>4.2.4.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>4.2.4.RELEASE</version>
		</dependency>

		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>3.8.1</version>
			<scope>test</scope>
		</dependency>
	</dependencies>
</project>
Create Student class

package com.javatutsworld.beans.inheritance;

public class Student {

	private String name;

	private String address;

	private String email;

	private String country;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getAddress() {
		return address;
	}

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

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public String getCountry() {
		return country;
	}

	public void setCountry(String country) {
		this.country = country;
	}

	@Override
	public String toString() {

		return "Name:" + name + " Address:" + address + " Email:" + email + " Country:" + country;
	}

}
Create spring beans.xml file where you define and show how to inherit the bean

<?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"
	xmlns:p="http://www.springframework.org/schema/p"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
        http://www.springframework.org/schema/context
  		http://www.springframework.org/schema/context/spring-context-3.2.xsd">

	<bean id="studentBase" class="com.javatutsworld.beans.inheritance.Student">
	<property name="country" value="UK"/>
	</bean>
	
	<bean id="studentChild" parent="studentBase">
	<property name="name" value="Mohd Saaim"/>
	<property name="address" value="Okhla Vihar Jamia Nagar New Delhi"/>
	<property name="email" value="mukarram.babli@gmail.com"/>
	</bean>
</beans>

Here studentChild bean is inheriting country property and its value, and adding new properties.

Create test class BeanInheritanceTest which shows the output of both beans.

package com.javatutsworld.beans.inheritance;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class BeanInheritanceTest {
	
	public static void main(String[] args) {
		ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("beans.xml");

		Student studentBase = (Student) applicationContext.getBean("studentBase");
		System.out.println(studentBase.toString());
		
		Student studentchild = (Student) applicationContext.getBean("studentChild");
		System.out.println(studentchild.toString());

	}

}
Output

Sep 23, 2016 4:03:32 AM org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@29952be0: startup date [Fri Sep 23 04:03:32 EDT 2016]; root of context hierarchy
Sep 23, 2016 4:03:32 AM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [beans.xml]
Name:null Address:null Email:null Country:UK
Name:Mohd Saaim Address:Okhla Vihar Jamia Nagar New Delhi Email:mukarram.babli@gmail.com Country:UK

Create Abstract Bean

You know Abstract classes in java that should not be instantiated.

In spring you need to add abstract attribute inside < bean > tag.

Beans.xml with abstract attribute

<?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"
	xmlns:p="http://www.springframework.org/schema/p"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
        http://www.springframework.org/schema/context
  		http://www.springframework.org/schema/context/spring-context-3.2.xsd">

	<bean id="studentBase" abstract="true">
	<property name="country" value="UK"/>
	</bean>
	
	<bean id="studentChild" parent="studentBase" class="com.javatutsworld.beans.inheritance.Student">
	<property name="name" value="Mohd Saaim"/>
	<property name="address" value="Okhla Vihar Jamia Nagar New Delhi"/>
	<property name="email" value="mukarram.babli@gmail.com"/>
	</bean>
</beans>

Here you make parent bean as abstract but you can give class name or not it is optional.

In this case you will not allow this bean to instantiate and it will give error when you try to instantiate this abstract bean.

Now test this abstract bean

package com.javatutsworld.beans.inheritance;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class BeanInheritanceTest {
	
	public static void main(String[] args) {
		ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("beans.xml");

		Student studentBase = (Student) applicationContext.getBean("studentBase");
		System.out.println(studentBase.toString());
		
		Student studentchild = (Student) applicationContext.getBean("studentChild");
		System.out.println(studentchild.toString());

	}

}
Output

Sep 23, 2016 5:44:52 AM org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@739474: startup date [Fri Sep 23 05:44:52 EDT 2016]; root of context hierarchy
Sep 23, 2016 5:44:52 AM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [beans.xml]
Exception in thread "main" org.springframework.beans.factory.BeanIsAbstractException: Error creating bean with name 'studentBase': Bean definition is abstract
	at org.springframework.beans.factory.support.AbstractBeanFactory.checkMergedBeanDefinition(AbstractBeanFactory.java:1288)
	at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:285)
	at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
	at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1054)
	at com.javatutsworld.beans.inheritance.BeanInheritanceTest.main(BeanInheritanceTest.java:10)

Overriding the bean value


<?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"
	xmlns:p="http://www.springframework.org/schema/p"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
        http://www.springframework.org/schema/context
  		http://www.springframework.org/schema/context/spring-context-3.2.xsd">

	<bean id="studentBase" abstract="true">
	<property name="country" value="UK"/>
	</bean>
	
	<bean id="studentChild" parent="studentBase" class="com.javatutsworld.beans.inheritance.Student">
	<property name="country" value="India"/>
	<property name="name" value="Mohd Saaim"/>
	<property name="address" value="Okhla Vihar Jamia Nagar New Delhi"/>
	<property name="email" value="mukarram.babli@gmail.com"/>
	</bean>
</beans>

Here you override the country property value in Child bean.


package com.javatutsworld.beans.inheritance;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class BeanInheritanceTest {
	
	public static void main(String[] args) {
		ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("beans.xml");

		/*Student studentBase = (Student) applicationContext.getBean("studentBase");
		System.out.println(studentBase.toString());*/
		
		Student studentchild = (Student) applicationContext.getBean("studentChild");
		System.out.println(studentchild.toString());

	}

}
Output

Sep 23, 2016 6:02:40 AM org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@5e8b957: startup date [Fri Sep 23 06:02:40 EDT 2016]; root of context hierarchy
Sep 23, 2016 6:02:41 AM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [beans.xml]
Name:Mohd Saaim Address:Okhla Vihar Jamia Nagar New Delhi Email:mukarram.babli@gmail.com Country:India

Here you got the new value India for Country in the child bean.

      Advertisements