I need to execute code BEFORE closing the context of the spring. The annotation method @Predestroy is already called AFTER the context is closed, and I get the error: The ApplicationContext is closed and the ConnectionFactory can no longer create connections.

    1 answer 1

    Use the event listener. Described here . You need to listen to the ContextClosedEvent event. The simplest example is below:

    package com.example; import org.springframework.context.ApplicationListener; import org.springframework.context.event.ContextClosedEvent; import org.springframework.stereotype.Component @Component public class MyClosedEventHandler implements ApplicationListener<ContextClosedEvent>{ public void onApplicationEvent(ContextClosedEventevent) { //здесь твоя обработка } } 
    • > ContextClosedEvent - Published when the ApplicationContext is closed - i.e. the event is raised again AFTER the context is closed - Andrew
    • What problem do you need to solve? Perhaps you should simply use the specific bean's life cycle tracking. In this case, you can look in the direction of DisposableBean - Temka also