没有调用Spring单例bean的@PreDestroy方法 [英] @PreDestroy method of a Spring singleton bean not called

查看:1384
本文介绍了没有调用Spring单例bean的@PreDestroy方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 beans.xml 中定义了一个Spring bean,如下所示:

I have a Spring bean defined in beans.xml as follows:

<context:annotation-config />
[...]
<bean id="myBackend" class="mycompany.BackendBean" scope="singleton" />

bean内部有2个方法,必须在Web应用程序的开始和结束之前执行:

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");
    }
}

当我运行服务器时( mvn jetty:运行),我可以在控制台中看到 init 方法的输出,我从中得出结论 init 方法已执行。

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.

当我按 Ctrl-C 和Jetty时开始关闭,我没有看到 destroy 方法的输出。

When I press Ctrl-C and Jetty starts to shut down, I don't see the output of the destroy method.

我应该改变什么当应用程序终止时,要执行 destroy 方法的订单?

What should I change in order for the destroy method to be executed, when the application is terminated?

推荐答案

对于Spring,当应用程序关闭时调用 @PreDestroy 回调方法,你必须添加一个关闭钩子并关闭它所在的应用程序上下文。你可以附加钩子如果它提供了这样的API,则使用 Runtime.getRuntime()。addShutdownHook(Thread)或者到Jetty。以下是使用JVM关闭钩子的方法:

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();
   }});

这篇关于没有调用Spring单例bean的@PreDestroy方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆