Registering a shutdown hook in Spring 2.5

前端 未结 2 1039
心在旅途
心在旅途 2020-12-31 15:43

I have a spring application which is not calling bean destroy methods on shutdown. I\'ve seen references to this being due to instantiation in a beanRefFactory, and that thi

相关标签:
2条回答
  • 2020-12-31 16:21

    This method is still available in ConfigurableApplicationContext and implemented by AbstractApplicationContext.

    So you might be able to do this

    ApplicationContext ctx = ...;
    if (ctx instanceof ConfigurableApplicationContext) {
        ((ConfigurableApplicationContext)ctx).registerShutdownHook();
    }
    

    Alternatively, you could simply call ((ConfigurableApplicationContext)ctx).close() yourself while closing down the application or using your own shutdown hook:

    Runtime.getRuntime().addShutdownHook(new Thread() {
        public void run(){
           if (ctx instanceof ConfigurableApplicationContext) {
               ((ConfigurableApplicationContext)ctx).close();
           }
        }
     });
    
    0 讨论(0)
  • 2020-12-31 16:46

    So many upvotes, but the second statement is totally wrong, a system.exit in java would terminate the spring before ever getting to your shutdownhook, the right way to go are these 4 ways

    1 InitializingBean and DisposableBean callback interfaces 2 Other Aware interfaces for specific behavior 3 custom init() and destroy() methods in bean configuration file 4 @PostConstruct and @PreDestroy annotations

    Click here!

    0 讨论(0)
提交回复
热议问题