Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/xslt/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如果bean初始化失败,请停止SpringWeb应用程序_Java_Spring_Servletcontextlistener - Fatal编程技术网

Java 如果bean初始化失败,请停止SpringWeb应用程序

Java 如果bean初始化失败,请停止SpringWeb应用程序,java,spring,servletcontextlistener,Java,Spring,Servletcontextlistener,我编写了一个customcontextloaderlistener,它在web应用程序启动时被调用 public class CustomContextLoaderListener extends ContextLoaderListener { private Logger log = Logger.getLogger(CustomContextLoaderListener.class); public void contextInitialized(ServletConte

我编写了一个customcontextloaderlistener,它在web应用程序启动时被调用

public class CustomContextLoaderListener  extends ContextLoaderListener {
    private Logger log = Logger.getLogger(CustomContextLoaderListener.class);

    public void contextInitialized(ServletContextEvent sce){

        WebApplicationContext wctx = new ContextLoader().initWebApplicationContext(sce.getServletContext());
        AppContext.setWebApplicationContext(wctx);
        wctx.getBeanDefinitionCount();
        String [] beanNames = wctx.getBeanDefinitionNames();
        for(String beanName : beanNames){
        log.info(beanName);
        }
现在,如果bean初始化中出现错误,我想停止web应用程序。所以我想我可以做这样的事情

    public class CustomContextLoaderListener  extends ContextLoaderListener {
        private Logger log = Logger.getLogger(CustomContextLoaderListener.class);

        public void contextInitialized(ServletContextEvent sce){

try {
            WebApplicationContext wctx = new ContextLoader().initWebApplicationContext(sce.getServletContext());
            AppContext.setWebApplicationContext(wctx);
            wctx.getBeanDefinitionCount();
            String [] beanNames = wctx.getBeanDefinitionNames();
            for(String beanName : beanNames){
            log.info(beanName);
            }
}catch(Exception e) {
      contextDestroyed(sce)
 }

public void contextDestroyed(ServletContextEvent sce) {

// not sure how should I stop the web app here..

any ideas

}

您可以执行以下操作:

private void callExceptionHandler(Exception exception) {
    logger.error("failed to create bean: ", exception);
    System.exit(1);
}
您可以从
contextInitialized
方法调用上述方法:

catch(Exception e) {
      callExceptionHandler(e)
 }

是的,我不确定是否要在我的web应用程序中使用system.exit。我投票将此问题视为离题,因为该问题说明了针对特定问题的建议解决方案,但随后邀请其他人提供一般性反馈或想法。要么将这个问题重新组织为一个问题,让原始海报回答他们自己的问题以供审查,要么将这个问题关闭,以支持其他看似重复的问题。