Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Known way to stop server when spring context failed to load?

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.

like image 727
Elad Tabak Avatar asked Oct 21 '22 03:10

Elad Tabak


1 Answers

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);
}
like image 98
Elad Tabak Avatar answered Oct 22 '22 18:10

Elad Tabak