Spring Bean Definition Inheritance
Spring Bean definition inheritance has nothing to do with Java class inheritance but inheritance concept is same. You can define a parent bean definition as a template and other child beans can inherit required configuration from the parent bean
Here is one simple example as Vehicle class is parent and Car class is child and Car class is getting wheel property via inheritance configured in the xml
Example
1. Create a Parent class (Vehicle.java)
package com.inheritance;public class Vehicle {private String wheel;public String getWheel() {return wheel;}public void setWheel(String wheel) {this.wheel = wheel;}}
2. Create a Child class (Car.java)
package com.inheritance;public class Car {private String dicky;private String wheel;public String getWheel() {return wheel;}public void setWheel(String wheel) {this.wheel = wheel;}public String getDicky() {return dicky;}public void setDicky(String dicky) {this.dicky = dicky;}}
3. Create Beans configuration file (Vehicle.xml)
Add bean details
<beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-2.5.xsd"><bean id="vehicle" class="com.inheritance.Vehicle"><property name="wheel" value="Four wheeler"/></bean><bean id="car" class="com.inheritance.Car"parent="vehicle"><property name="dicky" value="Flat dicky"/></bean></beans>
Note: In the above car bean definition mentioned the parent bean.
4. Create a Main program (CarMain.java)
package com.inheritance;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;public class CarMain {public static void main(String[] args) {ApplicationContext context = new ClassPathXmlApplicationContext("Vehicle.xml");Vehicle v = (Vehicle) context.getBean("vehicle");System.out.println("From Vehicle"+v.getWheel());Car c = (Car) context.getBean("car");System.out.println("From car"+c.getWheel());System.out.println("From car"+c.getDicky());}}
5. Project Structure
6. Output
From VehicleFour wheeler
From carFour wheeler
From carFlat dicky
From carFour wheeler
From carFlat dicky
No comments:
Post a Comment