Spring Boot如何暴露端点以检测应用是否处于启动中状态
如何给Spring Boot应用添加启动状态检测端点
你的Spring Boot应用启动耗时较长,想要在启动过程中暴露一个端点来查看当前是否处于启动状态。根据你提供的日志,Tomcat初始化完成、WebApplicationContext加载结束后,到应用完全启动之间的窗口就是需要端点生效的阶段,下面给你一个轻量的实现方案:
实现步骤
1. 创建状态存储类
先定义一个组件来保存启动状态,默认标记为「启动中」:
import org.springframework.stereotype.Component; @Component public class StartupStatusHolder { private boolean isStarting = true; public boolean isStarting() { return isStarting; } public void setStarted() { this.isStarting = false; } }
2. 监听启动完成事件
利用Spring的事件监听机制,在应用完全启动后更新状态:
import org.springframework.context.ApplicationListener; import org.springframework.context.event.ApplicationReadyEvent; import org.springframework.stereotype.Component; @Component public class StartupStatusListener implements ApplicationListener<ApplicationReadyEvent> { private final StartupStatusHolder statusHolder; public StartupStatusListener(StartupStatusHolder statusHolder) { this.statusHolder = statusHolder; } @Override public void onApplicationEvent(ApplicationReadyEvent event) { // 应用完全启动后,将状态切换为「已启动」 statusHolder.setStarted(); } }
3. 编写Controller暴露端点
这个Controller会在WebApplicationContext初始化完成后即可访问,正好对应你日志里>>> start to expose here的时间点:
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class StartupStatusController { private final StartupStatusHolder statusHolder; public StartupStatusController(StartupStatusHolder statusHolder) { this.statusHolder = statusHolder; } @GetMapping("/health/startup") public String checkStartupStatus() { return statusHolder.isStarting() ? "STARTING" : "STARTED"; } }
效果说明
- 当日志输出
Root WebApplicationContext: initialization completed之后,/health/startup端点就可以正常访问,返回STARTING; - 等应用完全启动(日志出现
Started Application),端点会自动返回STARTED。
如果不想自己实现基础逻辑,也可以用Spring Boot Actuator自定义健康指标,但上面的方案更轻量,无需额外引入依赖。
内容的提问来源于stack exchange,提问作者Thomas
相关产品推荐
相关产品推荐

