Spring Boot: exception while exiting application


December 2018


912 time


I want to run a Spring application that should exit after it has done its work. But in my implementation I get an exception.

build.gradle contains:

dependencies {
    compile("org.springframework.boot:spring-boot-starter-web") {
        exclude module: "spring-boot-starter-tomcat"


public class Application {

    private ApplicationContext context;

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

    public void doTheWorkAndExit() {
        // do the work ...
        SpringApplication.exit(context, () -> 0);


I get the exception

Exception thrown from LifecycleProcessor on context close

java.lang.IllegalStateException: LifecycleProcessor not initialized - call 'refresh' before invoking lifecycle methods via the context: org.springframework.context.annotation.AnnotationConfigAppl
[email protected]: startup date [Fri Mar 11 10:03:27 CET 2016]; root of context hierarchy
    at org.springframework.context.support.AbstractApplicationContext.getLifecycleProcessor(AbstractApplicationContext.java:415)
    at org.springframework.context.support.AbstractApplicationContext.doClose(AbstractApplicationContext.java:975)
    at org.springframework.context.support.AbstractApplicationContext.close(AbstractApplicationContext.java:934)
    at org.springframework.boot.SpringApplication.close(SpringApplication.java:1252)
    at org.springframework.boot.SpringApplication.exit(SpringApplication.java:1238)
    at mypackage.Application.doTheWorkAndExit(Application.java:34)

What can I do? Is there a better solution than using System.exit(0)?

1 answers


В Вашем Application.classвы можете реализовать CommandLineRunnerинтерфейс.

public class Application implements CommandLineRunner{}

После реализации необходимо реализовать метод недействительным run()

public void run(String... strings) {
    //here starts your code (like in a normal main method in a java application)

Приложение выключается после excecuting всего кода.

Полный Application.class:

public class Application implements CommandLineRunner{

  public void run(String... strings) {
      //here your code...

  public static void main(String[] args) throws Exception {
      SpringApplication.run(Application.class, args);