Pages

Thursday, August 2, 2012

life cycle call backs of Spring framework

Lets say you need to keep track of life cycle call backs of spring beans.

The first point is if you want to destroy all the beans you created using a certain context, then you need to get the AbstractApplicationContext type of context Object. Then by calling registerShutdownHook method on the instance, all the beans that are created using that context instance is destroyed when the method is finished executing.

AbstractApplicationContext context = new ClassPathApplicationContext("spring.xml");
context.registerShutdownHook();

If you want to do something after the properties are set in a certain bean, you need to implement the InitializingBean interface in the class. The interface implements afterPropertiesSet method.

if you want to do something just before the bean is destroyed, you need to implement DisposableBean interface. The interface implements destroy method and there you can include any cleanup codes.

public class Vehicle implements InitializingBean, DisposableBean{

     public void afterPropertiesSet() throws Exception{

    }
    public void destroy() throws Exception{

   }
}

Another way of handling the life cycle of a bean is to mention the methods in the bean tag

<bean id="car" class="org.Car" init-method="myInit" destroy-method="destroy" ></bean>
Now spring looks for the myInit when initializing and destroy method after finishing in the bean class.

Instead of doing the above we can do the following

<beans default-init-method="myInit" default-destroy-method="destroy" >

As above the default methods can be metioned in the beans tag which covers all the beans. However if the method is not found in the corresponding bean class, then spring will just ignore it.

If we use both the methods together, then the priority goes to the interface implementation. That is interface methods are called first and then the spring configuration methods gets called.


No comments:

Post a Comment