Searching...
Wednesday, 26 June 2013

Spring Bean Definition Template Example

11:53

Spring Bean Definition Template

We can create a Bean definition template which can be used by other child bean definitions without any additional coding. While defining a Bean Definition Template, you should not specify class attribute and should specify abstract attribute with a value of true as shown below:

Here is one simple example as Vechicle 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 (Vechicle.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 (VehicleTemplate.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/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
    <bean id="vehicle"   abstract="true">
    <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 (VehicleTemplateMain.java)

 

package com.inheritance;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class VehicleTemplateMain {

    /**
     * @param args
     */
    public static void main(String[] args) {

        ApplicationContext context = new ClassPathXmlApplicationContext(
                "VehicleTemplate.xml");
        Car c = (Car) context.getBean("car");
        System.out.println("From vehicle abstract   "+c.getWheel());
        System.out.println("From car"+c.getDicky());

    }

}

 

5. Output

 

From vehicle abstract   Four wheeler
From carFlat dicky

0 comments: