Spring Inversion of Control (IoC) also known as
Dependency Injection (DI) is a process by which
objects define their dependencies with collaborating objects.
Spring provides DisposableBean interface which allows us to
perform pre processing tasks when the container containing this bean is destroyed.
DisposableBean.java
package org.springframework.beans.factory;
public abstract interface DisposableBean
{
public abstract void destroy() throws Exception;
}
System.out.println("Initializing ApplicationContext");
ApplicationContext factory = new ClassPathXmlApplicationContext("destroy.xml");
System.out.println("ApplicationContext Initialized");
System.out.println("Accessing first bean");
SimpleDisposableBean first = (SimpleDisposableBean) factory.getBean("first");
System.out.println(first);
System.out.println("Accessing second bean");
SimpleDisposableBean second = (SimpleDisposableBean) factory.getBean("second");
System.out.println(second);
/**
* Register a Shutdown hook for graceful Shutdown.
* Calls the relevant destroy methods on your singleton beans
* so that all resources are released
*/
AbstractApplicationContext abc = (AbstractApplicationContext ) factory;
abc.registerShutdownHook();
}
}
It gives the following output,
Initializing ApplicationContext
ApplicationContext Initialized
Accessing first bean
SimpleDisposableBean[FIRST]
Accessing second bean
SimpleDisposableBean[SECOND]
In destroy callback : SECOND
In destroy callback : null
In destroy callback : FIRST
In destroy callback : null