Sometimes during development, something gets broken which cause the spring context to fail loading. The problem is that sometimes the error is just in some bean(s), but the rest of the webapp is partially loading, and then you get some weird behaviors.
Is there a known way to make Spring stop the server process in case something bad happened? like some bean failed injection, or some NPE happened in some PostConstruct or something.
Something like stopOnError=true in web.xml.
So eventually the solution I found is: Create a class that implements ServletContextListener, call it ApplicationLoaderListener.
Set this class in web.xml:
<listener>
<listener-class>com.my.package.ApplicationLoaderListener</listener-class>
</listener>
Add a private member to it:
private final ServletContextListener loader = new ContextLoaderListener();
This class must implement the two interface methods, which the relevant one is contextInizialized:
@Override
public void contextInitialized(ServletContextEvent sce) {
try {
loader.contextInitialized(sce);
} catch (BeanCreationException e) {
handle(e);
}
}
And the implementation of handle():
private void handle(BeanCreationException e) {
log.error("=============== FATAL =============== - failed to create bean: ", e);
System.exit(1);
}
And to make the code complete, the second method:
@Override
public void contextDestroyed(ServletContextEvent sce) {
loader.contextDestroyed(sce);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With