如何在ServletContextListener中exception时中止Tomcat启动?

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

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

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

尝试指定:

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

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

如果为true,则在服务器初始化阶段发生exception时服务器将退出。

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

更新:

如果你想通过代码执行此操作, System.exit()工作?

 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会如何反应……

如果您因为webapp未能部署而要停止Tomcat,我假设您没有将其他应用程序部署到tomcat。 在这种情况下,为什么不将此应用程序构建为具有嵌入式Tomcat / Jetty的独立Web应用程序? 这样,只要您的webapp无法正常启动,嵌入式服务器也将关闭。

对我来说,看起来你专注于ServletContextListener来解决ServletContextListener适合的问题。

不要使用System.exit()因为它会杀死可能运行其他已部署应用程序的服务器。 如果没关系,因为你知道永远不会有其他应用程序(而且你不想),那就制作一个独立的webapp。 这种不良做法在CWE中被列为潜在的弱点: CWE-382

只是一个提示:spring boot有助于构建带有嵌入式服务器的独立webapp。 请参阅此指南: https : //spring.io/guides/gs/spring-boot/

好文章解释了为什么这可能是你正在寻找的: http : //www.beyondjava.net/blog/application-servers-sort-of-dead/