stop the spring web application if a bean initialization fails
Asked Answered
A

1

3

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);
        }

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

}
Ander answered 26/5, 2016 at 23:39 Comment(1)
I'm voting to close this question as off-topic because the question is stating a proposed solution to a specific problem but then invites others to give general feedback or ideas. Either this question should be restructured as a question where the original poster answers their own question for review or this question should just be closed in favor of other seemingly duplicate questions.Canna
P
-1

You could do something like below:

private void callExceptionHandler(Exception exception) {
    logger.error("failed to create bean: ", exception);
    System.exit(1);
}

You could call above method from contextInitialized method:

catch(Exception e) {
      callExceptionHandler(e)
 }
Parthenia answered 27/5, 2016 at 3:41 Comment(1)
Yeah I am not sure if I would like to use system.exit in my web appAnder

© 2022 - 2024 — McMap. All rights reserved.