【问题标题】:Spring boot return exit code for CommandLine app命令行应用程序的 Spring Boot 返回退出代码
【发布时间】:2016-12-29 03:19:50
【问题描述】:

我有一个 Spring Boot 应用程序实现了 CommandLineRunner。如果发生任何错误/异常,我想返回 -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);
}
...
}

我尝试过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

请帮忙!

【问题讨论】:

  • 也许您应该将System.exit(-1) 移动到public void run 并且不要在主目录中使用它。
  • 谢谢@Patrick,我也试过了,仍然返回 0。
  • 您的第一个来源提到了 ExitCodeGenerator。您唯一缺少的是调用 SpringApplication.exit,请参阅下面的答案。

标签: java spring-boot exit-code


【解决方案1】:

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;
    }
}

【讨论】:

  • 如果您有多个跑步者,这是一个有效的解决方案,因为它不会强制退出吗?
  • @Wolsie 调用所有 ExitCodeGenerator 的 getExitCode 函数,然后由 SpringApplication.exit 返回生成的退出代码并传递给 System.exit,它会终止 VM,即只要您没有 System.exit。在其他任何地方退出,VM 在所有 ExitGenerator 都执行了它们的 getExitCode 函数后终止。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-09-12
  • 1970-01-01
  • 2017-10-08
  • 2010-09-24
  • 1970-01-01
  • 2018-06-18
相关资源
最近更新 更多