首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >为什么PreDestroy方法不起作用

为什么PreDestroy方法不起作用
EN

Stack Overflow用户
提问于 2018-02-27 16:27:26
回答 1查看 1.3K关注 0票数 0

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

代码语言:javascript
复制
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");
    }
}

配置:

代码语言:javascript
复制
<bean id="greetingService"
      class="com.example.hello.GreetingServiceImpl"
      init-method="init"
      destroy-method="destroy">

这是我的测试代码:

代码语言:javascript
复制
@Test
public void greeting() {
    ConfigurableApplicationContext context = new ClassPathXmlApplicationContext("applicationConfig.xml");
    GreetingService greetingService = context.getBean(GreetingService.class);

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

当我运行这段代码时,我没有在日志中看到销毁方法,也没有看到上下文关闭。

代码语言:javascript
复制
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,但结果是相同的。

EN

回答 1

Stack Overflow用户

发布于 2018-02-27 16:40:33

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

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

然后注入您的应用程序上下文或注入相应的bean

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/49004215

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档