简体   繁体   English

Spring Web Application:如果初始化失败,则关闭

[英]Spring Web Application: Shutdown if initialization fails

I have a Spring web application. 我有一个Spring Web应用程序。 When the application context has started I use ApplicationListener<ContextRefreshedEvent> to perform some application initalization, in particular I load data from a web service. 当应用程序上下文启动时,我使用ApplicationListener<ContextRefreshedEvent>进行一些应用程序初始化,尤其是从Web服务加载数据。 If this web service is not reachable then my application cannot do anything useful and it does not make sense to keep it running. 如果无法访问此Web服务,则我的应用程序将无法做任何有用的事情,并且使其保持运行状态也没有意义。 Is there a way to programmatically shutdown the application context? 有没有办法以编程方式关闭应用程序上下文?

I have tried to do the following: 我尝试执行以下操作:

if (contextRefreshedEvent instanceof ConfigurableApplicationContext)
{
    ConfigurableApplicationContext configurableApplicationContext
            = (ConfigurableApplicationContext) contextRefreshedEvent;
    configurableApplicationContext.close ();
}

However rather then closing gracefully that produces the following exception: 但是,而不是优雅地关闭会产生以下异常:

java.lang.IllegalStateException: BeanFactory not initialized or already closed - call 'refresh' before accessing beans via the ApplicationContext java.lang.IllegalStateException:BeanFactory未初始化或已关闭-在通过ApplicationContext访问Bean之前调用“刷新”

So what is the proper way to shutdown the application in such a situation? 那么在这种情况下关闭应用程序的正确方法是什么?

Throw an ApplicationContextException . 抛出一个ApplicationContextException It worked for me with Spring 4.2.7.RELEASE 它适用于Spring 4.2.7.RELEASE

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM