提问者:小点点

如果bean初始化失败,则停止Spring Web应用程序


我编写了一个自定义contextloaderlistener,它在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

}

共1个答案

匿名用户

你可以做下面这样的事情:

private void callExceptionHandler(Exception exception) {
    logger.error("failed to create bean: ", exception);
    System.exit(1);
}

您可以从contextFirst ated方法调用上述方法:

catch(Exception e) {
      callExceptionHandler(e)
 }