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

后端 未结 1 1399
眼角桃花
眼角桃花 2021-01-01 05:09

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

相关标签:
1条回答
  • 2021-01-01 05:35

    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);
    }
    
    0 讨论(0)
提交回复
热议问题