0

I have a basic spring project with simple configuration. This is 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");
    }
}

configuration:

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

And this is my test code:

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

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

When I run this code I don't see destroy method in logs as well as context closing.

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

I tried to call registerShutdownHook and refresh but result was the same.

Kirill
  • 1,540
  • 4
  • 18
  • 41

1 Answers1

0

not quite sure, haven't tested it, but have you tried making your destroy method public?

For testing I would suggest you use the spring testing annotations: https://docs.spring.io/spring/docs/current/spring-framework-reference/testing.html#integration-testing-annotations

and then inject your application context or inject the corresponding bean

claudegex
  • 285
  • 1
  • 4
  • 15
  • It's ok if `PreDestroy` method is private. `PostConstruct` method is private and it works fine – Kirill Feb 27 '18 at 08:46
  • 1
    Yes, it should work with private. Just wanted you to check if this could be a specific problem with the Spring version you use. I tested your code snippets with 5.0.4.RELEASE - and destroy method is executed. What version do you use and which dependencies have you defined? – claudegex Feb 27 '18 at 09:02