How to close the @SpringBootTest context before JVM's shutdown hook is called (once, after all JUnit tests)

Viewed 1515

Q. How to close the Spring Boot context, created by annotating a test class with @SpringBootTest, before JUnit 5 stops the JVM (which calls the hooks added with addShutdownHook()) ?


Example:
Assuming a bean like this

@Component
public class SomeBean implements DisposableBean {

    public SomeBean() {
        var hook = new Thread(() -> System.out.println("Shutdown Hook called"));
        Runtime.getRuntime().addShutdownHook(hook);
    }

    @Override
    public void destroy() {
        System.out.println("Destroy called");
    }
}

and a simple Junit 5 test like this:

@SpringBootTest
class TestJvmShutdownHookApplicationTests {

    @Test
    void contextLoads() {
    }

}

how do I get the call to destroy() to be performed before the JVM shutdown hook?

2021-02-18 13:54:24.540  INFO 18928 --- [           main] .a.t.TestJvmShutdownHookApplicationTests : Started TestJvmShutdownHookApplicationTests in 2.378 seconds (JVM running for 3.687)
Shutdown Hook called
2021-02-18 13:54:24.863  INFO 18928 --- [extShutdownHook] o.s.s.concurrent.ThreadPoolTaskExecutor  : Shutting down ExecutorService 'applicationTaskExecutor'
Destroy called

Background it.ozimov:embedded-redis adds a JVM shutdown hook and closes the Redis server before the bean redisConnectionFactory (Lettuce) is destroyed.

1 Answers
Related