【问题标题】:Why PreDestroy method doesn't work为什么 PreDestroy 方法不起作用
【发布时间】:2018-08-06 20:05:04
【问题描述】:

我有一个配置简单的基本 spring 项目。这是豆子

public class GreetingServiceImpl implements GreetingService {
    private final Log log = LogFactory.getLog(getClass());

    @Override
    public String hello() {
        return "Hello";
    }

    private void init() {
        log.info("GreetingServiceImpl INIT");
    }

    private void destroy() {
        log.info("GreetingServiceImpl DESTROY");
    }
}

配置:

<bean id="greetingService"
      class="com.example.hello.GreetingServiceImpl"
      init-method="init"
      destroy-method="destroy">

这是我的测试代码:

@Test
public void greeting() {
    ConfigurableApplicationContext context = new ClassPathXmlApplicationContext("applicationConfig.xml");
    GreetingService greetingService = context.getBean(GreetingService.class);

    Assert.assertEquals("Hello", greetingService.hello());
    context.close();
}

当我运行此代码时,我在日志中看不到 destroy 方法以及上下文关闭。

org.springframework.context.support.AbstractApplicationContext prepareRefresh
Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@2be94b0f
org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
Loading XML bean definitions from class path resource [applicationConfig.xml]
com.example.hello.GreetingServiceImpl init
GreetingServiceImpl INIT

Process finished with exit code 0

我尝试调用registerShutdownHookrefresh,但结果相同。

【问题讨论】:

    标签: java spring lifecycle predestroy


    【解决方案1】:

    不太确定,还没有测试过,但是您是否尝试过公开您的销毁方法?

    对于测试,我建议您使用弹簧测试注释:https://docs.spring.io/spring/docs/current/spring-framework-reference/testing.html#integration-testing-annotations

    然后注入你的应用上下文或者注入相应的bean

    【讨论】:

    • PreDestroy 方法是私有的就可以了。 PostConstruct 方法是私有的,它工作正常
    • 是的,它应该适用于私人。只是想让您检查这是否是您使用的 Spring 版本的特定问题。我用 5.0.4.RELEASE 测试了你的代码 sn-ps - 并执行了 destroy 方法。您使用什么版本以及定义了哪些依赖项?
    猜你喜欢
    • 2023-03-03
    • 2013-01-22
    • 2012-01-14
    • 2015-11-07
    • 2015-12-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多