Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/blackberry/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 命令行应用程序的弹簧引导返回退出代码_Java_Spring Boot_Exit Code - Fatal编程技术网

Java 命令行应用程序的弹簧引导返回退出代码

Java 命令行应用程序的弹簧引导返回退出代码,java,spring-boot,exit-code,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... a

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

我在这里尝试了以下解决方案:


请帮忙

上有一篇很好的文章回答了你的问题。要点如下:

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

也许你应该将
System.exit(-1)
移动到
public void run
中,并且不要在main中使用它。谢谢@Patrick,我也尝试了,仍然返回0。你的第一个来源提到了ExitCodeGenerator。您唯一缺少的是调用SpringApplication.exit,请参阅下面的答案。如果您有多个运行程序,这是一个有效的解决方案,因为它不会强制退出吗?@Wolsie调用所有ExitCodeGenerator的getExitCode函数,然后SpringApplication.exit返回生成的退出代码并传递给System.exit,这会终止VM,即只要您没有System.exit,VM就会在所有ExitGenerator执行其getExitCode函数后终止。