Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Force a Spring Boot application to exit when there's an exception

Tags:

spring-boot

I have a Spring Boot command line application that is supposed to run once in a container, then exit (every 10min).

I had an issue initially because it would not exit, even after executing correctly. I fixed it like that, by injecting the context and calling exit with it :

@SpringBootApplication
@Slf4j
public class EmailKpiTrackerApplication implements CommandLineRunner {

  private final EmailKpiTracker emailKpiTracker;

  private final ConfigurableApplicationContext context;

  public EmailKpiTrackerApplication(EmailKpiTracker emailKpiTracker, ConfigurableApplicationContext context) {

    this.emailKpiTracker = emailKpiTracker;
    this.context=context;
  }

  public static void main(String[] args) {
    SpringApplication.run(EmailKpiTrackerApplication.class, args).close();
  }

  @Override
  public void run(String... args) throws Exception {
  
      emailKpiTracker.recordNewProcessedEmails();
      System.exit(SpringApplication.exit(context));
  }
}

But I have one issue left : if the application fails to start, then it will not exit. The JVM keeps running, and the container doesn't shut down.

How can I force the Spring Boot app to exit, whether it ran successfully or there was a major issue during the run ?

Thanks

like image 280
Vincent F Avatar asked Sep 11 '25 01:09

Vincent F


1 Answers

It was not too difficult.. but not obvious either. I fixed it by catching the exception and forcing to exit in the finally block :

@SpringBootApplication
@Slf4j
public class EmailKpiTrackerApplication implements CommandLineRunner {

  private final EmailKpiTracker emailKpiTracker;

  private final ConfigurableApplicationContext context;

  public EmailKpiTrackerApplication(EmailKpiTracker emailKpiTracker, ConfigurableApplicationContext context) {

    this.emailKpiTracker = emailKpiTracker;
    this.context=context;
  }

  public static void main(String[] args) {
    SpringApplication.run(EmailKpiTrackerApplication.class, args).close();
  }

  @Override
  public void run(String... args) throws Exception {
    try {
      emailKpiTracker.recordNewProcessedEmails();
    }
    catch(Exception e){
      log.error("problem running the application",e);
    }
    finally {
      System.exit(SpringApplication.exit(context));
    }
  }
}
like image 141
Vincent F Avatar answered Sep 12 '25 22:09

Vincent F