Programmatically shut down Spring Boot application

Cover Image for Programmatically shut down Spring Boot application
Matheus Mello
Matheus Mello
published a few days ago. updated a few hours ago

🛑 Shutting Down a Spring Boot Application Programmatically 🛑

So, you've built an awesome Spring Boot application and now you want to gracefully shut it down programmatically, without terminating the VM? Well, you've come to the right place! In this blog post, we'll explore the answer to this common question and provide you with some easy solutions. Let's dive right in! 💪

The Opposite of new SpringApplication(Main.class).run(args);

To understand how to programmatically shut down a Spring Boot application, let's first discuss the opposite. When you start your Spring Boot application using the SpringApplication.run() method, it spins up a web server and begins listening for incoming requests.

But how can we stop this gracefully without forcefully terminating the VM? 🤔

Solution 1: Using the SpringApplication.exit() Method

One simple and straightforward way to shut down a Spring Boot application programmatically is by using the SpringApplication.exit() method. This method allows you to gracefully stop the application by triggering the shutdown process.

Here's how you can do it:

SpringApplication application = new SpringApplication(Main.class);
ConfigurableApplicationContext context = application.run(args);

// ... Your awesome application logic ...

// Now, let's gracefully shut down the application
int exitCode = SpringApplication.exit(context);
System.exit(exitCode);

In this approach, we first start the application using SpringApplication.run(), perform any necessary tasks, and then trigger the shutdown process by calling SpringApplication.exit() with the application context. Finally, we use System.exit() to terminate the VM gracefully.

Solution 2: Using a Custom Endpoint

Another way to shut down a Spring Boot application programmatically is by exposing a custom management endpoint. This approach allows you to trigger the shutdown process by sending an HTTP request to a specific endpoint.

Here's how you can implement it:

  1. Add the Spring Boot Actuator dependency to your pom.xml file:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
  1. Create a custom controller that listens for shutdown requests:

@RestController
public class ShutdownController {

    @Autowired
    private ApplicationContext context;

    @PostMapping("/shutdown")
    public void shutdown() {
        SpringApplication.exit(context, () -> 0);
    }
}
  1. Secure the shutdown endpoint (optional):

@Configuration
public class ActuatorSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/shutdown").hasRole("ADMIN")
                .anyRequest().permitAll()
                .and()
                .csrf().disable();
    }
}

In this solution, we create a custom controller with a shutdown() method that calls SpringApplication.exit() with the application context. You can secure the endpoint by using Spring Security and restrict access to authorized users only.

Conclusion

And that's it! You now have two easy solutions to programmatically shut down your Spring Boot application without terminating the VM. Feel free to choose the approach that best fits your requirements.

Whether you're gracefully shutting down your application to perform a clean restart or adding a convenient API endpoint for remote shutdown, these methods will surely come in handy. So go ahead, implement them in your code, and enjoy the ease of programmatically shutting down your Spring Boot application!

Do you have any other Spring Boot questions or interesting use cases? Share them in the comments below and let's continue the conversation! 😄👇


More Stories

Cover Image for How can I echo a newline in a batch file?

How can I echo a newline in a batch file?

updated a few hours ago
batch-filenewlinewindows

🔥 💻 🆒 Title: "Getting a Fresh Start: How to Echo a Newline in a Batch File" Introduction: Hey there, tech enthusiasts! Have you ever found yourself in a sticky situation with your batch file output? We've got your back! In this exciting blog post, we

Matheus Mello
Matheus Mello
Cover Image for How do I run Redis on Windows?

How do I run Redis on Windows?

updated a few hours ago
rediswindows

# Running Redis on Windows: Easy Solutions for Redis Enthusiasts! 🚀 Redis is a powerful and popular in-memory data structure store that offers blazing-fast performance and versatility. However, if you're a Windows user, you might have stumbled upon the c

Matheus Mello
Matheus Mello
Cover Image for Best way to strip punctuation from a string

Best way to strip punctuation from a string

updated a few hours ago
punctuationpythonstring

# The Art of Stripping Punctuation: Simplifying Your Strings 💥✂️ Are you tired of dealing with pesky punctuation marks that cause chaos in your strings? Have no fear, for we have a solution that will strip those buggers away and leave your texts clean an

Matheus Mello
Matheus Mello
Cover Image for Purge or recreate a Ruby on Rails database

Purge or recreate a Ruby on Rails database

updated a few hours ago
rakeruby-on-railsruby-on-rails-3

# Purge or Recreate a Ruby on Rails Database: A Simple Guide 🚀 So, you have a Ruby on Rails database that's full of data, and you're now considering deleting everything and starting from scratch. Should you purge the database or recreate it? 🤔 Well, my

Matheus Mello
Matheus Mello