23.9 Application exit application 退出

每个SpringApplication将在JVM上注册一个关闭钩子,以确保ApplicationContext在退出时优雅地关闭。所有标准的Spring生命周期回调(例如DisposableBean接口,或者@PreDestroy 注释)都可以使用。

此外,bean还可以实现 org.springframework.boot.ExitCodeGenerator SHI

并添加资源文件application.properties:

name: JavaChen


Application启动类

@SpringBootApplication
public class Springboot239Application implements CommandLineRunner {
   @Autowired
   private HelloWorldService helloWorldService;
   public static void main(String[] args) {
      SpringApplication.run(Springboot239Application.class, args);
   }
   @Override
   public void run(String... args) {
      System.out.println(this.helloWorldService.getMessage());
      if (args.length > 0 && args[0].equals("exitcode")) {
         throw new ExitException();
      }
   }
}

如果一些CommandLineRunner beans被定义必须以特定的次序调用,你可以额外实现org.springframework.core.Ordered接口或使用@Order注解。

利用command-line runner的这个特性,再配合依赖注入,可以在应用程序启动时后首先引入一些依赖bean,例如data source、rpc服务或者其他模块等等,这些对象的初始化可以放在run方法中。不过,需要注意的是,在run方法中执行初始化动作的时候一旦遇到任何异常,都会使得应用程序停止运行,因此最好利用try/catch语句处理可能遇到的异常。

每个SpringApplication在退出时为了确保ApplicationContext被优雅的关闭,将会注册一个JVM的shutdown钩子。所有标准的Spring生命周期回调(比如,DisposableBean接口或@PreDestroy注解)都能使用。

此外,如果beans想在应用结束时返回一个特定的退出码,可以实现org.springframework.boot.ExitCodeGenerator接口,例如上面例子中的ExitException异常类:

public class ExitException extends RuntimeException implements ExitCodeGenerator {
    @Override
    public int getExitCode() {
        return 10;
    }
}
@Component
public class HelloWorldService {
    @Value("${name:World}")
    private String name;

    public String getMessage() {
        return "Hello " + this.name;
    https://github.com/csg103/springboot23-9}
}

源码地址  https://github.com/csg103/springboot23-9

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值