Spring - Bean Inheritance
Spring also provides us a way to implement inheritance with beans
Just imagine 'Car' class has two attributes 'brand' and 'type' . Now, lets assume 'brand' property will be initialized in one bean and the 'type' property in the other bean. Now, how would you link them? Bean definition Inheritance is the solution.
Let us see with the below example :
Car Class
class Car {
String brand;
String type;
// -- Getters and Setters --
}
application-context.xml
<?xml version = "1.0" encoding = "UTF-8"?>
<beans xmlns = "http://www.springframework.org/schema/beans"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean name="carParent" class = "Car">
<property name = "brand" value="Honda" />
</bean>
<bean name="car" class = "Car" parent="carParent">
<property name = "type" value="Four Wheeler" />
</bean>
</beans >
Just note in the above XML, we have initialized the 'brand' property in a bean 'carParent'. And the 'type' property in a bean 'car'. Now, since both are separate beans, we have joined them using parent="carParent" in the 'Car' bean.
Which simply means, the 'car' bean has inherited all the properties of 'carParent'.
Finally, in the main() method we define our application code to interact with spring.
import org.springframework.context.ApplicationContext;
public class FirstSpringApp {
public static void main(String[] args) {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("application-context.xml");
Car car = (Car)applicationContext.getBean("car");
System.out.println("The value is : "+car.getType());
System.out.println("This is parent value obtained by Car : "+car.getBrand());
}
Output :
The value is : Honda
This is parent value obtained by Car : Four Wheeler
As we can see that we are just getting the 'car' bean
Car car = (Car)applicationContext.getBean("car");
<bean name="car" class = "Car" parent="carParent">
<property name = "type" value="Four Wheeler" />
</bean>
And able to fetch both 'type' and 'brand' property(As the 'brand' property is in 'carParent' bean).
It is only possible because of parent="carParent", which defines inheritance of beans.