0

I have written a spring boot application for file uploading. I want my spring boot application to shutdown the running localhost 8080 after its execution has been completed .

Is there any possible ways to kill the server after the spring boot execution is completed

Could someone help me on this

want to kill the localhost programmatically.

Praveen s
  • 7
  • 3

2 Answers2

1

You can do this in the following way by creating a bean:

@Component
class ShutdownManager {
@Autowired
private ApplicationContext appContext;
public void initiateShutdown(int returnCode){
    SpringApplication.exit(appContext, () -> returnCode);
}

}

You can autowire this bean anywhere and use the initiateShutdown function to close teh application context and server like this:

@Component
public class Controller{
@Autowired
private final ShutdownManager shutdownManager;
  @GetMapping("/")
public void Shutdown(){
   shutdownManager.initiateShutdown(0);
}
}

Or you can simply Autowire this bean on any controller and call this method any where you want with the return code.

Sumit
  • 407
  • 1
  • 8
0

just put this code at end of your uploading code:

@Controller
public class Upload {

    @Autowired
    private ApplicationContext context;

    @PostMapping("/upload")
    public void uploadFile(){

    // do upload the file here.
    //after uploading shutdown the spring boot application.

    SpringApplication.exit(context, (ExitCodeGenerator) () -> 0);

       }    

     }

I have checked it myself it is working.

  • There is no need to explicitly call `System.exit`. `SpringApplication.run` returns a `ConfigurableApplicationContext` which implements `Closeable`. Once the context is closed, the application exists. So in other words: `try (ConfigurableApplicationContext context = SpringApplication.run(BlogAppApplication.class, args) { /* do nothing */ }` – Rob Spoor Oct 10 '22 at 09:04
  • Keep in mind that both will not exit at the right time, which should be after the request has been handled. – Rob Spoor Oct 10 '22 at 09:06