Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to close a spring ApplicationContext?

Tags:

java

spring

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.

like image 564
Avner Levy Avatar asked Jan 20 '13 11:01

Avner Levy


People also ask

How do I close an application context object?

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.

How do you close a context?

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.

How do you stop spring boot gracefully?

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.


1 Answers

Downcast your ApplicationContext to ConfigurableApplicationContext which defines close() method:

((ConfigurableApplicationContext)appCtx).close(); 
like image 177
Tomasz Nurkiewicz Avatar answered Oct 05 '22 18:10

Tomasz Nurkiewicz