springboot中自定义退出码

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了springboot中自定义退出码相关的知识,希望对你有一定的参考价值。


在sprintboot中,因为是大多数情况下,用application的方式去运行的,那么当程序退出的时候,其实是有个exitcode的,正常退出的时候,exitcode为0,否则为1,某些情况下,是可以自定义exitcode,可以用下面的方法:

 

@SpringBootApplication
public class SampleApplication implements ExitCodeGenerator

public static void main(String[] args)
System.exit(SpringApplication
.exit(SpringApplication.run(SampleApplication.class, args)));


@Override
public int getExitCode()
return 25;

  这里只需要实现ExitCodeGenerator就可以了,重写getExitCode()方法,返回自定义码。

而且我们可以监听退出的事件:
 

@Bean
SampleEventListener sampleEventListener()
return new SampleEventListener();


private static class SampleEventListener

@EventListener
public void exitEvent(ExitCodeEvent event)
LOG.info("Application Exit code: ", event.getExitCode());

还可以监听发生何种异常的时候,就使用什么样的退出码进行退出,比如:
 

@Bean
ExitCodeExceptionMapper exitCodeToexceptionMapper()
return exception ->

if (exception.getCause() instanceof NumberFormatException)
return 34;

if (exception.getCause() instanceof CustomTypeException)
return 45;

...
return 1;
;

 

以上是关于springboot中自定义退出码的主要内容,如果未能解决你的问题,请参考以下文章

详解Springboot中自定义SpringMVC配置

java SpringBoot中自定义参数校验

springboot中自定义异常以及定制异常界面

SpringBoot项目中自定义注解的使用

Springboot 获取.yml中自定义参数

springboot中自定义根路径的配置