Spring Boot 返回 CommandLine 应用程序的退出代码

ter*_*ung 7 java exit-code spring-boot

我有一个实现了 CommandLineRunner 的 Spring Boot 应用程序。如果发生任何错误/异常,我想返回 -1 作为退出代码,如果没有异常,则返回 0。

public class MyApplication implements CommandLineRunner{
private static Logger logger = LoggerFactory.getLogger(MyApplication.class);

@Override
public void run(String... args) throws Exception {
    // to do stuff. exception may happen here.
}

public static void main(String[] args) {
    try{
        readSetting(args);
        SpringApplication.run(MyApplication.class, args).close();
    }catch(Exception e){
        logger.error("######## main ########");
        java.util.Date end_time = new java.util.Date();                                         
        logger.error(e.getMessage(), e);
        logger.error(SystemConfig.AppName + " System issue end at " + end_time);
        System.exit(-1);
    }
    System.exit(0);
}
...
}
Run Code Online (Sandbox Code Playgroud)

我尝试过System.exit(),SpringApplication.exit(MyApplication.context,exitCodeGenerator)等,但当我抛出异常时它仍然返回0!

我已经尝试过这里的解决方案:

https://sdqali.in/blog/2016/04/17/programmable-exit-codes-for-spring-command-line-applications/

http://www.programcreek.com/java-api-examples/index.php?class=org.springframework.boot.SpringApplication&method=exit

请帮忙!

Mad*_*din 14

https://www.baeldung.com/spring-boot-exit-codes上有一篇很好的文章回答了您的问题。要点如下:

@SpringBootApplication
public class CLI implements CommandLineRunner, ExitCodeGenerator {

    private int exitCode; // initialized with 0

    public static void main(String... args) {
        System.exit(SpringApplication.exit(SpringApplication.run(CLI.class, args)));
    }

    /**
     * This is overridden from CommandLineRunner
     */
    @Override
    public void run(String... args) {
        // Do what you have to do, but don't call System.exit in your code
        this.exitCode = 1;
    }

    /**
     * This is overridden from ExitCodeGenerator
     */
    @Override
    public int getExitCode() {
        return this.exitCode;
    }
}
Run Code Online (Sandbox Code Playgroud)