从ApplicationListener关闭spring应用程序

时间:2019-07-01 14:32:33

标签: java spring spring-boot

是否可以从ApplicationListener关闭上下文?

   public class MyListener implements ApplicationListener<ContextRefreshedEvent> {

    @Override
        public void onApplicationEvent(ContextRefreshedEvent event) {
            // on some certain condition we want to shutdown spring ie close the context
        ((ConfigurableApplicationContext)event.getApplicationContext()).close();
        }
    }

问题在于,Spring仍然希望在这里完成启动过程:

public static void main(String[] args) {
        SpringApplication.run(MyApplication.class, args);
}

并因此引发一个IllegalStateException:

  

java.lang.IllegalStateException:   org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext@dcb84c98   已经关闭

2 个答案:

答案 0 :(得分:2)

您似乎真正想问的问题是“如何中断Spring-Boot启动”。

从您的<input type="radio" class="form-control"/> <input type="text" class="form-control"/> 方法中引发异常。

答案 1 :(得分:0)

似乎您想在启动时中断 Spring。

简单,您将无法做到这一点而不会出错。

如果您仍然想在启动时终止应用程序,请使用:

System.exit(0);

但是,如果您想在开头后关闭上下文,则可以收听名为ApplicationReadyEvent的另一个Spring event

@Component
public class MyListener {

    @EventListener
    public void onApplicationEvent(ApplicationReadyEvent event) throws Exception {
        event.getApplicationContext().close();
    }
}
  

ApplicationReadyEvent-尽可能晚发布的事件,表明该应用程序是    *准备服务请求