Difference between ExitCodeGenerator and System.exit(0)

烂漫一生 提交于 2021-02-10 12:17:06

问题


I recently learned that the proper way to shut down a Spring Boot application is this:

public class Application {

    @Bean
    public ExitCodeGenerator exitCodeGenerator() {
        return new ExitCodeGenerator() {
            @Override
            public int getExitCode() {
                return 0;
            }
        };
    }

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

This should return an exit code of 0, or whatever I configure it to return in the getExitCode() method. My question is - what is the difference between doing the approach above vs the one below:

public class Application {

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

The application seems to be shut down in exactly the same way by both approaches, at least in the console. So what's the difference?


回答1:


Of course for you examples, this does not matter. But what this allows is to "glue" a certain Exception to a certain exit code. Spring, by default, catches all Exceptions that your code might throw - if such an Exception also implements ExitCodeGenerator - that will be used to output the exit code you have provided.

Of course, you can do that mapping by hand, but it's a lot more verbose and harder to maintain; Spring makes this easier. Once that is understood, you might also be interested in ExitCodeExceptionMapper that can map an underlying Exception (with let's say multiple error messages) to different error codes.




回答2:


The ExitCodeGenerator is used if you 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.

For example:

@SpringBootApplication
public class ExitCodeApplication {

@Bean
public ExitCodeGenerator exitCodeGenerator() {
    return new ExitCodeGenerator() {
        @Override
        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.



来源:https://stackoverflow.com/questions/48572612/difference-between-exitcodegenerator-and-system-exit0

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!