从 ApplicationListener 关闭 spring 应用程序 [英] Shutdown spring application from ApplicationListener

查看:24
本文介绍了从 ApplicationListener 关闭 spring 应用程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Is it possible to close the context from an 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还想在这里完成启动过程:

The problem is that Spring still wants to finish the startup process here:

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

因此抛出一个 IllegalStateException:

And therefore throws an IllegalStateException:

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

java.lang.IllegalStateException: org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext@dcb84c98 has been closed already

推荐答案

您真正想问的问题似乎是如何中断 Spring-Boot 启动".

It seems likely that the question you actually wanted to ask is "How do I interrupt Spring-Boot startup".

从您的 onApplicationEvent 方法中抛出异常.

Throw an exception from your onApplicationEvent method.

这篇关于从 ApplicationListener 关闭 spring 应用程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆