How to shut down a Spring Boot command-line application

Solution 1:

I found a solution. You can use this:

public static void main(String[] args) {
    SpringApplication.run(RsscollectorApplication.class, args).close();
    System.out.println("done");
}

Just use .close() on run.

Solution 2:

The answer depends on what it is that is still doing work. You can probably find out with a thread dump (eg using jstack). But if it is anything that was started by Spring you should be able to use ConfigurableApplicationContext.close() to stop the app in your main() method (or in the CommandLineRunner).

Solution 3:

This is a combination of @EliuX answer with @Quan Vo one. Thank you both!

The main different is I pass the SpringApplication.exit(context) response code as a parameter to the System.exit() so if there is an error closing the Spring context you will notice.

The SpringApplication.exit() will close the Spring context.

The System.exit() will close the application.

@Component
public class OneTimeRunner implements CommandLineRunner {

    @Autowired
    private ConfigurableApplicationContext context;

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