有时在开发过程中,某些东西被破坏导致 spring 上下文加载失败。 问题是有时错误只是在某些 bean 中,但 webapp 的其余部分正在部分加载,然后你会得到一些奇怪的行为。
是否有一种已知的方法可以让 Spring 在发生不良情况时停止服务器进程?比如一些 bean 注入(inject)失败,或者一些 NPE 发生在一些 PostConstruct 或其他东西中。
类似于 web.xml 中的 stopOnError=true。
最佳答案
所以最终我找到的解决方案是: 创建一个实现 ServletContextListener 的类,将其命名为 ApplicationLoaderListener。
在 web.xml 中设置这个类:
<listener>
<listener-class>com.my.package.ApplicationLoaderListener</listener-class>
</listener>
为其添加一个私有(private)成员:
private final ServletContextListener loader = new ContextLoaderListener();
此类必须实现两个接口(interface)方法,相关的方法是 contextInizialized:
@Override
public void contextInitialized(ServletContextEvent sce) {
try {
loader.contextInitialized(sce);
} catch (BeanCreationException e) {
handle(e);
}
}
以及handle()的实现:
private void handle(BeanCreationException e) {
log.error("=============== FATAL =============== - failed to create bean: ", e);
System.exit(1);
}
而为了使代码完整,第二种方法:
@Override
public void contextDestroyed(ServletContextEvent sce) {
loader.contextDestroyed(sce);
}
关于java - 当 spring 上下文加载失败时停止服务器的已知方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25347593/