Monday, 16 July 2018

Programmatically shut down Spring Boot application

There are couple of ways to close the spring boot application.

a.   Close the application context by calling close method.
b.   Use exit method of SpringApplication

Close the application context by calling close method.
ConfigurableApplicationContext applicationContext = SpringApplication.run(Application.class, args);
applicationContext.close();

Application.java
package com.sample.myApp;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.ConfigurableApplicationContext;

@SpringBootApplication
public class Application {

 public static void main(String args[]) {
  ConfigurableApplicationContext applicationContext = SpringApplication.run(Application.class, args);

  System.out.println("Closing the application");

  applicationContext.close();
 }
}

Use exit method of SpringApplication
package com.sample.myApp;

import org.springframework.boot.ExitCodeGenerator;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.ConfigurableApplicationContext;

@SpringBootApplication
public class Application {

 public static void main(String args[]) {
  ConfigurableApplicationContext applicationContext = SpringApplication.run(Application.class, args);

  System.out.println("Closing the application");

        int exitCode = SpringApplication.exit(applicationContext, new ExitCodeGenerator() {
            @Override
            public int getExitCode() {
                return 0;
            }
        });
        
        //System.exit(exitCode);
 }
}





Previous                                                 Next                                                 Home

No comments:

Post a Comment