This post will discuss how to shut down a Spring Boot application.

1. Using ApplicationContext#close() method

Since closing the Spring Application basically means closing the underlying ApplicationContext. The idea is to use the close() method to close the application context, releasing all resources and locks that the implementation might hold. We can get ApplicationContext as a ConfigurableApplicationContext using SpringApplication.run() method, as shown below:

2. Using SpringApplication#exit() method

Alternatively, we can use SpringApplication.exit(ApplicationContext, ExitCodeGenerator…) static utility method, as shown in the following example:

 
Using Java 8 Lambda, we can rewrite the above code as:

 
We can also autowire ApplicationContext into one of our controllers and initiate app shut down from the controller itself, as shown below:

That’s all about shutting down a Spring Boot application.