Search This Blog

Tuesday, 24 April 2012

Creating default init and destroy methods

In earlier post we saw how Spring allowed us to define custom init and destroy methods - both via configuration and via code.As we are working with cars, we will need to check the engine on all cars before use and clean the car after use.
The xml configuration comes up with  a set of attributes that allows us to define common init and destroy methods for all beans defined in the same context.
<?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:p="http://www.springframework.org/schema/p"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"
    default-init-method="checkEngine" default-destroy-method="cleanCar">

    <bean id="car1" class="com.car.CustomInitDestroyCar" autowire="byName"/>
    <bean id="car2" class="com.car.CustomInitDestroyCar" autowire="byName"/>

    <bean id="combustEngine" class="com.car.Engine" p:name="Combusto" />
</beans>
Rather than defining init-method and destroy-method on every bean, we have defined the methods at the context level.
I tested the above beans:
public static void main(String[] args) {
    XmlBeanFactory beanFactory = new XmlBeanFactory(new ClassPathResource("default-init-destroy-beans.xml"));
    CustomInitDestroyCar car1 = (CustomInitDestroyCar) beanFactory.getBean("car1");
    System.out.println(car1.describe());
    CustomInitDestroyCar car2 = (CustomInitDestroyCar) beanFactory.getBean("car2");
    System.out.println(car2.describe());
    beanFactory.destroyBean("car1",car1);
    beanFactory.destroyBean("car2",car2);
}
The output indicates that the init and destroy methods were called for each of the beans.
Creating object
Setting the properties
Checking if engine is fine
Car in use com.car.CustomInitDestroyCar@fec107, engine is Engine - com.car.Engine@132e13d and name Combusto
Creating object
Setting the properties
Checking if engine is fine
Car in use com.car.CustomInitDestroyCar@1617189, engine is Engine - com.car.Engine@132e13d and name Combusto
Cleaning the car after use
Cleaning the car after use

No comments:

Post a Comment