简体   繁体   中英

Spring boot return exit code for CommandLine app

I have a Spring Boot application implemented CommandLineRunner. I wanted to return -1 as exit code if there is any error/exception happens and return 0 if no exception.

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

I have tried System.exit(), SpringApplication.exit(MyApplication.context, exitCodeGenerator), etc. But it still return 0 when I throw an exception!

I have tried solutions from here:

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

Please help!

There is a nice article answering your question on https://www.baeldung.com/spring-boot-exit-codes . Here is the gist:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM