Sunday, December 10, 2017

Spring - Execute a init method when initializing bean and destroying bean.

There are couple of ways to achieve this requirement.

First methodology
You can simply implements below interfaces in the bean

  • InitializingBean
  • DisposableBean
Then you have to override below methods respectively above interfaces. 

  • afterPropertiesSet()
  • destroy()
Note: You have to use registerShutdownHook (link) to see the effect of the destroy method.

Second methodology
In this scenario, I would like to introduce the way we can execute the custom method when initializing and destroying beans.

Initially, you have to implement custom methods for init and destroy as below
    public void myInit() {
        System.out.println("This is the custom init method");
    }
....
    public void myDestroy() {
        System.out.println("This is the custom destroy method");
    }

In the bean configuration file you have to tell to the Spring what are the init and destroy methods as below.
<beans>
    <bean id="student" class="com.home.model.Student" init-method="myInit" destroy-method="myDestroy">
        .....
    </bean>
.....
.....
</beans>

Enjoy...!!!


Tuesday, December 5, 2017

Spring - How to destroy beans when application shutdown? (registerShutdownHook)

If someone needs to destroy the beans when shutdown then application, what you need to do is:
  • Create a 'AbstractApplicationContext'
  • call the 'registerShutdownHook'
Find the below code for your reference

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

Once this "registerShutdownHook()" method executes, it destroy the beans when down the application.


Enjoy..!!