【转载】Springboot 项目启动、关闭 的监听
- 前言
想在项目启动或是关闭的时候, 做些事情。
例如启动时,打印输出 “你好” , 关闭时,打印输出 “再见”。
示例:
- 正文
其实方式很多,但是我推荐 根据官方白皮的建议做。
- 启动的监听:
如果需要在SpringApplication启动后运行某些特定代码,可以实现ApplicationRunner或CommandLineRunner接口。两个接口以相同的方式工作,并提供一个单独的运行方法,该方法在SpringApplication.run(…) 完成。
- 关闭的监听
每个SpringApplication都向JVM注册一个关闭挂钩,以确保ApplicationContext在退出时正常关闭。可以使用所有标准的Spring生命周期回调(如DisposableBean接口或@PreDestroy注释)。
- 示例使用代码
StandGuard.java
import org.springframework.beans.factory.DisposableBean; import org.springframework.boot.ApplicationArguments; import org.springframework.boot.ApplicationRunner; import org.springframework.stereotype.Component; @Component public class StandGuard implements ApplicationRunner, DisposableBean { @Override public void run(ApplicationArguments args) { System.out.println("你好。"); } @Override public void destroy() { System.out.println("再见!"); } }
- 效果
本文来自博客园,作者:Lz_蚂蚱,转载请注明原文链接:https://www.cnblogs.com/leizia/p/17259873.html
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步