If I run a spring boot application from within a Windows Command Prompt (using java -jar), and I press Control-C to terminate the process, I get the following console output, and the process remains opened:
2017-11-27 20:15:22,713 INFO [Thread-11] (AnnotationConfigEmbeddedWebApplicationContext:984) - Closing org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@6057aebb: startup date [Mon Nov 27 20:14:22 IST 2017]; parent: org.springframework.context.annotation.AnnotationConfigApplicationContext@2df9b86
I use the following code in order to listen to the ContextClosedEvent.
@Component
public class ListenerClass {
@EventListener
public void handleContextClose(ContextClosedEvent event) {
shutdown(); // This method has System.exit(SpringApplication.exit(ctx)); inside it
}
}
I tried adding the following code to the above-mentioned ListenerClass, but it didn't solve this issue:
@EventListener
public void handleContextStop(ContextStoppedEvent event) {
shutdown();
}
How can I cause the application to terminate when Control-C is pressed?
Your listener is not being reached (verify using debugger). Otherwise System.exit would kill all the threads - by the way, it is bad practice.
You should connect to your JVM up and running via jvisualvm, and check the live thread(s) once you hit ^C