After my application finishes I want to close the spring context.
The relevant code has an ApplicationContext
reference but I couldn't find a close
method.
private static void closeAsCloseable() { try (ConfigurableApplicationContext applicationContext = new AnnotationConfigApplicationContext( Application. class)) { // Additional logic... } } When the try block finishes, the close method - from Closeable - is called. This has the same effect as closing manually.
Emitting a Cancellation Event This can be done using the WithCancel function in the context package, which returns a context object, and a function. This function takes no arguments, and does not return anything, and is called when you want to cancel the context.
Close ApplicationContext Another option to shutdown Spring Boot application is to close Spring ApplicationContext using SpringApplication . SpringApplication#run(String…) method returns ApplicationContext as a < ConfigurableApplicationContext. We can use close() method to close ApplicationContext programmatically.
Downcast your ApplicationContext
to ConfigurableApplicationContext
which defines close()
method:
((ConfigurableApplicationContext)appCtx).close();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With