当Spring上下文无法加载时,停止服务器的已知方法是什么? [英] Known way to stop server when spring context failed to load?

查看:201
本文介绍了当Spring上下文无法加载时,停止服务器的已知方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有时在开发过程中,某些东西损坏了,从而导致spring上下文无法加载. 问题是,有时错误仅出现在某些Bean中,但是Webapp的其余部分正在部分加载,然后您会得到一些奇怪的行为.

Sometimes during development, something gets broken which cause the spring context to fail loading. The problem is that sometimes the error is just in some bean(s), but the rest of the webapp is partially loading, and then you get some weird behaviors.

是否有一种已知的方法可以使Spring在发生错误的情况下停止服务器进程?例如某些bean注入失败,或者某些NPE发生在某些PostConstruct之类的东西中.

Is there a known way to make Spring stop the server process in case something bad happened? like some bean failed injection, or some NPE happened in some PostConstruct or something.

类似于web.xml中的stopOnError = true.

Something like stopOnError=true in web.xml.

推荐答案

所以最终我找到的解决方案是: 创建一个实现ServletContextListener的类,将其称为ApplicationLoaderListener.

So eventually the solution I found is: Create a class that implements ServletContextListener, call it ApplicationLoaderListener.

在web.xml中设置此类:

Set this class in web.xml:

<listener>
    <listener-class>com.my.package.ApplicationLoaderListener</listener-class>
</listener>

向其添加私人成员:

private final ServletContextListener loader = new ContextLoaderListener();

此类必须实现两种接口方法,其中的一种是contextInizialized:

This class must implement the two interface methods, which the relevant one is contextInizialized:

@Override
public void contextInitialized(ServletContextEvent sce) {
    try {
        loader.contextInitialized(sce);
    } catch (BeanCreationException e) {
        handle(e);
    }
}

以及handle()的实现:

And the implementation of handle():

private void handle(BeanCreationException e) {
    log.error("=============== FATAL =============== - failed to create bean: ", e);
    System.exit(1);
}

并使代码完整,第二种方法:

And to make the code complete, the second method:

@Override
public void contextDestroyed(ServletContextEvent sce) {
    loader.contextDestroyed(sce);
}

这篇关于当Spring上下文无法加载时,停止服务器的已知方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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