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

时间:2016-12-29 03:19:51

标签: java spring-boot exit-code

我有一个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

请帮忙!

1 个答案:

答案 0 :(得分:1)

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

gn gen out