Spring bean container provides a powerful and flexible way to manage Spring bean’s lifecycle. If a Spring bean needs to clean itself up when Spring bean container is gracefully shutting down, it has several ways of specifying that intent. The intrusive and not recommended way is to implement the DisposableBean interface. A better way is to specify a call back method in the bean’s definition using the ‘destroy-method’ attribute. Spring 2.0’s convention over configuration model provides a very convenient way to eliminate the need to specify a call back method at the individual bean level. This new feature allows you to specify a convention at the application level using the ‘default-destroy-method’ attribute of the ‘beans’ XML element and if needed this convention can be overridden at the individual bean level.
So the question is how does Spring bean container knows when to shut itself down? The answer is it depends (I bet you heard that before). A Spring bean container usually is used in two environments: web-based application or standalone Java application. If it is the latter environment, then your application’s initialization step must call the method ‘registerShutdownHook’ of your choice of ApplicationContext implementation (BTW, method ‘registerShutdownHook’ is in the AbstractApplicationContext class). Then you may ask what exactly does the method ‘registerShutdownHook’ do? Apparently the Java JVM has a facility for a Java application to register a call back thread such that this thread will be given a chance to run during the JMV shutdown sequence. So method ‘registerShutdownHook’ calls ‘Runtime.addShutdownHook’ method and passes in anonymous class that extends Thread class and the ‘run’ method implementation contains a single call to a Spring bean container method to perform context closing, which publishes a ‘ContextClosedEvent’ and cleans up the singletons cache. During the singleton cache cleanup process is when Spring bean container will call each singleton bean’s cleanup call back method.
What’s about when a Spring bean container is used in web-based application environment? Does it have to call the same ‘registerShutdownHook’ method? Well, as it turns out, Spring bean container leverages the servlet context call back mechanism through the ‘ServletContextListener’ interface. Typically a Spring powered web-based application uses ‘ContextLoaderListener’ to bootstrap Spring’s root WebApplicationContext and ‘ContextLoaderListener’ implements ServletContextListener interface.
So now you understand how Spring bean container knows when to call your bean’s clean up method, my question is have you ever developed a Spring bean that needs to perform some sort of clean up? If so, what’s does your bean need to clean up?