本文介绍了如果bean初始化失败,则停止spring Web应用程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我已经编写了一个customcontextloaderlistener,它在Web应用程序启动时被调用.
I have written a customcontextloaderlistener and it gets called when the web application starts up.
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应用程序.所以我想我可以做这样的事情.
Now if there is an error in bean initialization I would like to stop the web application. So I am thinking I can do something like this.
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
方法调用上述方法:
You could call above method from contextInitialized
method:
catch(Exception e) {
callExceptionHandler(e)
}
这篇关于如果bean初始化失败,则停止spring Web应用程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!