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

Viewed 644

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

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));
    }
  }
}
Related