springspring-bootspring-beanshutdown-hookgraceful-shutdown

Getting BeanCreationNotAllowedException on spring graceful shutdown


My spring boot application uses spring boot graceful shutdown setting. In the app I'm having queue listeners in the separate threads. Everything gets shut down correctly except that every now and then I get error BeanCreationNotAllowedException Singleton bean creation not allowed while singletons of this factory are in destruction (Do not request a bean from a BeanFactory in a destroy method implementation!). It happens because in my listener I'm calling beanFactory.getBean but the bean destroy was already initiated, hence the error.

Is there any way to make spring boot wait longer with destroying of the beans?


Solution

  • I made it work. I'm using ApplicationListener and adding Thread.sleep on shutdown. This is executed before spring starts actual shutdown so it delays the destruction of the beans.

    @Component
    @RequiredArgsConstructor
    public class GracefulShutdownListener implements ApplicationListener<ContextClosedEvent> {
    
        private long shutdownDelayInMiliseconds = 3000;
    
    
        @Override
        public void onApplicationEvent(ContextClosedEvent event) {
    
           // here I can trigger any additional cleanup
    
            try {
                Thread.sleep(shutdownDelayInMiliseconds);
            } catch (InterruptedException interruptedException) {
                Thread.currentThread().interrupt();
            }
    
        }
    }