为什么预销毁方法不起作用



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

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

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

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,但结果是相同的。

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

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

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

相关内容

  • 没有找到相关文章

最新更新