简介
本文介绍SpringBoot退出时执行的方法。
注意
如果是通过命令:java -jar LearnSpringBoot-0.0.1-SNAPSHOT.jar,则直接ctrl+c,可以执行到下边的退出方法。
如果是用Idea启动,则按下Exit(注意不是红色的Stop)可以执行到下边的退出方法。
如果你用的mvn spring-boot:run来启动运行的话,可能不会执行销毁的操作。
法1:实现ApplicationListener接口(推荐)
@Component
public class MyTest implements ApplicationListener<ContextClosedEvent> {
@Override
public void onApplicationEvent(ContextClosedEvent event) {
System.out.println("ContextClosedEvent");
}
}
法2:实现DisposableBean
@Component
public class MyTest implements DisposableBean {
@Override
public void destroy() throws Exception {
System.out.println("销毁:DisposableBeanImpl.destroy");
}
}
法3:@PreDestroy注解
此注解的执行顺序在DisposableBean实现类的destroy方法之前。
package com.example.test;
import org.springframework.stereotype.Component;
import javax.annotation.PreDestroy;
@Component
public class MyTest {
@PreDestroy
public void destory() {
System.out.println("销毁:@PreDestory");
}
}

请先 !