【问题标题】:how to close the application during startup in spring boot如何在spring boot启动期间关闭应用程序
【发布时间】:2019-04-11 19:42:29
【问题描述】:

我有一个关于spring boot的启动的问题,如何在启动的时候关闭应用程序,例如我有以下

application.yml

ansi:
   true

我有以下@Configuration 类:

@Configuration
class AppConfig {
   @Value('${ansi}')
   String ansi;


   @Bean
   getAnsi() {
        if(ansi.equals("true")) {
             Ansi ansiObj = new Ansi();
             ansiObj.ansi = ansi;
             return ansiObj;
        }
   }
}

class Ansi {
   String ansi;
}

application.yml中的ansitrue时,它继续,否则,应用程序应该关闭,我们可以在创建bean的过程中关闭应用程序吗?这是一个好习惯吗?有什么好的方法可以处理吗?

【问题讨论】:

标签: java spring-boot


【解决方案1】:

我们有很多选项可以关闭 spring-boot 应用程序:

关闭休息端点 - 将以下属性添加到您的 application.properties 并触发以下请求 curl -X POST localhost:port/actuator/shutdown

management.endpoints.web.exposure.include=*  
management.endpoint.shutdown.enabled=true  
endpoints.shutdown.enabled=true

你也可以调用合适的方法来关闭应用程序:

  • 通过在ConfigurableApplicationContext 对象上调用方法close()(它将关闭应用程序上下文)
  • 通过将退出代码传递给方法SpringApplication.exit(ctx, () -> 0);

请查看this 文章了解更多详情。

【讨论】:

    【解决方案2】:

    如果 bean 抛出异常,则 Spring 将不会继续,进程将结束。

    if(ansi.equals("true")) {
         Ansi ansiObj = new Ansi();
         ansiObj.ansi = ansi;
         return ansiObj;
    }
    else  {
        throw new IllegalArgumentException("reason");
    }
    

    我不能说我曾经有过它的用例,但我不会说这是必要的坏习惯。在这个有限的真假例子中,似乎有点不寻常。如果您需要对属性进行约束,例如X

    【讨论】:

      猜你喜欢
      • 2017-01-14
      • 2021-10-27
      • 1970-01-01
      • 1970-01-01
      • 2021-11-19
      • 2015-10-14
      • 2019-08-15
      • 2017-03-06
      • 1970-01-01
      相关资源
      最近更新 更多