Running the program will give the same output as the other two mechanisms.
The destruction callback is an ideal mechanism for ensuring that your applications shut down
gracefully and do not leave resources open or in an inconsistent state. However, you still have to decide
whether to use the destruction method callback, the DisposableBean interface, or the @PreDestroy
annotation. Again, let the requirements of your application drive your decision in this respect; use the
method callback where portability is an issue, and use the DisposableBean interface or a JSR-250
annotation to reduce the amount of configuration required.
Order of Resolution
As with the case of bean creation, you can use all mechanisms on the same bean instance for bean
destruction. In this case, Spring invokes the method annotated with @PreDestroy first and then
DisposableBean.destroy(), followed by your destroy method.
Using a Shutdown Hook
The only drawback of the destruction callbacks in Spring is that they are not fired automatically; you need
to remember to call AbstractApplicationContext.destroy() before your application is closed. When your
application runs as a servlet, you can simply call destroy() in the servlet's destroy() method. However, in
a stand-alone application, things are not quite so simple, especially if you have multiple exit points out of
your application. Fortunately, there is a solution. Java allows you to create a shutdown hook, a thread that
is executed just before the application shuts down. This is the perfect way to invoke the destroy() method
of your AbstractApplicationContext (which was being extended by all concrete ApplicationContext
implementations). The easiest way to take advantage of this mechanism is to use the
AbstractApplicationContext's registerShutdownHook() method. The method automatically instructs
Spring to register a shutdown hook of the underlying JVM runtime. This is shown in Listing 5-12.
Listing 5-12. Registering a Shutdown Hook
package com.apress.prospring3.ch5.lifecycle;
import org.springframework.context.support.GenericXmlApplicationContext;
public class ShutdownHookExample {
public static void main(String[] args) {
GenericXmlApplicationContext ctx = new GenericXmlApplicationContext();
ctx.load("classpath:lifecycle/disposeInterface.xml");
ctx.registerShutdownHook();
ctx.refresh();
DestructiveBeanWithInterface bean = (DestructiveBeanWithInterface)
ctx.getBean("destructiveBean");
}
}
Running this example results in the following output:
Initializing Bean
Destroying Bean
As you can see, the destroy() method is invoked, even though we didn't write any code to invoke it
explicitly as the application was shutting down.
Search WWH :
Custom Search
Previous Page
Spring Framework 3 Topic Index
Next Page
Spring Framework 3 Bookmarks
Home