springboot 系统停止时 触发的方法
时间: 2023-10-29 16:06:09 浏览: 45
在 Spring Boot 中,可以通过实现 ApplicationRunner 或 CommandLineRunner 接口来在系统启动时执行一些初始化操作,类似地,可以通过实现 DisposableBean 接口在系统停止时执行一些清理操作。
另外,可以使用 Spring Boot 提供的 ShutdownEndpoint 来触发系统停止,并执行一些清理操作。具体方法如下:
1. 在 pom.xml 中添加依赖:
```
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
```
2. 在配置文件中添加以下配置:
```
management.endpoints.web.exposure.include=shutdown
```
3. 实现 ShutdownEndpoint 的 shutdown() 方法,放置在需要执行清理操作的类中:
```
@Component
public class MyShutdownEndpoint implements ShutdownEndpoint {
@Override
public void shutdown() {
// 执行清理操作
}
}
```
4. 启动应用后,可以通过 HTTP POST 请求来触发系统停止:
```
POST http://localhost:8080/actuator/shutdown
```