gpt4 book ai didi

java - 命令行应用程序的 Spring Boot 返回退出代码

转载 作者:行者123 更新时间:2023-12-05 01:01:40 26 4
gpt4 key购买 nike

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

请帮忙!

最佳答案

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

关于java - 命令行应用程序的 Spring Boot 返回退出代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41372705/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com