spring boot 1.5x 优雅停机

2022-01-29 14:30

优雅停机的英文为 graceful shutdown 看官方文档。

还可以返回自定义的exit code

23.9 Application exit
Each SpringApplication will register a shutdown hook with the JVM to ensure that the ApplicationContext is closed gracefully on exit. All the standard Spring lifecycle callbacks (such as the DisposableBean interface, or the @PreDestroy annotation) can be used.

In addition, beans may implement the org.springframework.boot.ExitCodeGenerator interface if they wish to return a specific exit code when SpringApplication.exit() is called. This exit code can then be passed to System.exit() to return it as a status code.

public class ExitCodeApplication {

public ExitCodeGenerator exitCodeGenerator() {
return new ExitCodeGenerator() {
public int getExitCode() {
return 42;

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

Also, the ExitCodeGenerator interface may be implemented by exceptions. When such an exception is encountered, Spring Boot will return the exit code provided by the implemented getExitCode() method.