@PreDestroy method of a Spring singleton bean not called
spring
Solution
For Spring to call `@PreDestroy` callback method when you application shuts down, you have to add a shutdown hook and close the application context it in. You could attach the hook to JVM using `Runtime.getRuntime().addShutdownHook(Thread)` or to Jetty if it provides such an API. Here is how you'd do it with JVM shutdown hook:
final ApplicationContext appContext = ... // create your application context
// using one of the various application context classes
Runtime.getRuntime().addShutdownHook(new Thread() {
public void run() {
appContext.close();
}});
Problem
I have a Spring bean defined in `beans.xml` as follows: ``` <context:annotation-config /> [...] <bean id="myBackend" class="mycompany.BackendBean" scope="singleton" /> ``` Inside the bean are 2 methods, which must be executed at the start and before termination of the web application: ``` public class BackendBean implements IBackend { private static final Logger LOGGER = LoggerFactory .getLogger(BackendBean.class); @PostConstruct public void init() { LOGGER.debug("init"); } @PreDestroy public void destroy() { LOGGER.debug("destroy"); } } ``` When I run the server (`mvn jetty:run`), I can see the output of the `init` method in the console, from which I conclude that the `init` method is executed. When I press `Ctrl-C` and Jetty starts to shut down, I don't see the output of the `destroy` method. What should I change in order for the `destroy` method to be executed, when the application is terminated?