【转载】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("再见!");
}
}
  • 效果

posted @   Lz_蚂蚱  阅读(687)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示
评论
收藏
关注
推荐
深色
回顶
收起