如何在 ServletContextListener 中出现异常时中止 Tomcat 启动? [英] How to abort Tomcat startup upon exception in ServletContextListener?

查看:63
本文介绍了如何在 ServletContextListener 中出现异常时中止 Tomcat 启动?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个实现 ServletContextListener 的类,它在启动时加载一些资源.

I have a class implementing ServletContextListener that loads some resources upon startup.

这些资源对应用程序至关重要,当我的逻辑中发生一些不良事件时,我希望整个启动失败.

Those resources are critical to the application in a way that I would like to fail the whole startup when some bad event happens in my logic.

是否可以从 ServletContextListener.contextInitialized() 方法内部执行任何命令来停止和失败整个 Tomcat 启动?

Is there any command I can execute from inside the ServletContextListener.contextInitialized() method to stop and fail the whole Tomcat startup?

推荐答案

尝试指定:

-Dorg.apache.catalina.startup.EXIT_ON_INIT_FAILURE=true

在您的 java 运行时选项中,引用 官方文档:

in your java runtime options, quoting official documentation:

如果为true,如果在服务器初始化阶段发生异常,服务器将退出.

If true, the server will exit if an exception happens during the server initialization phase.

如果未指定,将使用默认值 false.

If not specified, the default value of false will be used.

更新:

如果你想通过代码来做到这一点,System.exit()会起作用吗?

If you want to do this by code, will System.exit() work?

public class FailFastListener implements ServletContextListener {
    
    private static final Logger log = LoggerFactory.getLogger(FailFastListener.class);
    
    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {
        try {
            //initialization
        } catch(Exception e) {
            log.error("Sooo bad, shutting down", e);
            System.exit(1);
        }
    }

    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {
    }
}

您可以使用 模式来包装现有的听众而不会使他们杂乱无章.不知道 Tomcat 会如何反应你...

You can use decorator pattern to wrap existing listeners without cluttering them. Not sure how will Tomcat react thou...

这篇关于如何在 ServletContextListener 中出现异常时中止 Tomcat 启动?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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