Spring shutdown event that fires immediately before ApplicationContext is destroyed?

|▌冷眼眸甩不掉的悲伤 提交于 2021-02-20 14:14:34

问题


I am looking for an interceptor or a trigger to know that, all the context beans are destroyed and the applicationcontext instance is about to destroy itself. So I can do one process at the end of the application lifetime.

There is this event type ContextClosedEvent, which is close to the thing that I wanna do but, it throws the event after destruction of beans. I thing it comes with the close() method of the applicationcontext. So it doesn't fit to my need

Any ideas?

Regards

Ali


回答1:


You can use registerShutDownHook() method of the abstract application context class. For more details have a look at this.

UPDATE

Then you should try @PreDestroy annotation on top of the method where you want to run something in the end when the spring context is about to destroy.

Hope this helps you. Cheers.




回答2:


Create a bean implementing SmartLifecycle, with a getPhase returning Integer.MAX_VALUE. Its stop() method will be executed before any other stop or destroy methods. You can there do cleanup on every resources in living beans.



    @Component
    public class Terminator implements SmartLifecycle {

        private boolean started = true;

        @Override
        public void stop() {
            // CLEANUP CODE
        }
        @Override
        public void stop(Runnable callback) {
            stop();
            callback.run();
        }

        @Override
        public int getPhase() {
            return Integer.MAX_VALUE;
        }
        @Override
        public boolean isAutoStartup() {
            return true;
        }
        @Override
        public boolean isRunning() {
            return started;
        }

    }


来源:https://stackoverflow.com/questions/10902775/spring-shutdown-event-that-fires-immediately-before-applicationcontext-is-destro

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!