- 利用Spring Application的事件机制监听 ContextClosedEvent 事件
@EventListener
public void listen(ContextClosedEvent event) {
log.info("context will be closed immediately.. {}", event);
}
- 使用javax自带的 @PreDestroy 注解
@PreDestroy
public void close() {
log.info("application is closing!");
}
- 实现 ServletContextListener 中的 contextDestroyed 方法
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
public class MyServletContextListener implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent event) {
// do something after init
}
@Override
public void contextDestroyed(ServletContextEvent event) {
// do something before destroyed
}
}
在配置类中注册该listener就行
@Bean
ServletListenerRegistrationBean<ServletContextListener> myServletListener() {
ServletListenerRegistrationBean<ServletContextListener> bean = new ServletListenerRegistrationBean<>();
bean.setListener(new MyServletContextListener());
return bean;
}