应用启动和关闭监听器功能分析 一、功能概述ApplicationStartAndStopListener是一个 Spring Boot 应用启动和关闭监听器用于记录系统的启动和关闭时间到数据库并实现优雅停机机制。二、使用背景在系统运行过程中需要记录系统的启动和关闭时间以便进行系统运行时间统计系统稳定性监控故障排查和日志分析优雅停机确保资源正确释放三、核心实现3.1 类定义Slf4jComponentpublicclassApplicationStartAndStopListenerimplementsApplicationRunner{privatefinalSysStartLogServicesysStartLogService;privatefinalConfigurableApplicationContextcontext;privatefinalbooleanstartLogEnabled;}实现接口ApplicationRunner- 在应用启动后执行依赖注入SysStartLogService: 系统启动日志服务ConfigurableApplicationContext: Spring 应用上下文startLogEnabled: 是否启用启动日志配置项3.2 应用启动处理Overridepublicvoidrun(ApplicationArgumentsargs){if(!startLogEnabled){return;}try{DatestartTimenewDate();log.info(启动时间DateUtil.format(startTime,DatePattern.NORM_DATETIME_PATTERN));// 获取数据库中 id 最大的一条数据SysStartLogsysStartLogsysStartLogService.getOne(Wrappers.SysStartLoglambdaQuery().orderByDesc(SysStartLog::getId).last(limit 1));// 更新启动时间if(sysStartLog!null){sysStartLog.setStartTime(startTime);sysStartLogService.updateById(sysStartLog);}}catch(Exceptione){log.warn(添加到系统启动日志表失败e.getMessage());}shutdownHook(context);}处理流程应用启动 ↓ 检查 startLogEnabled 配置 ↓ 获取当前启动时间 ↓ 查询数据库中最新的一条启动日志 ↓ 更新启动时间 ↓ 注册关闭钩子3.3 应用关闭处理privatevoidshutdownHook(ConfigurableApplicationContextrun){Runtime.getRuntime().addShutdownHook(newThread(()-{DateendTimenewDate();System.out.println(开始执行优雅停机逻辑...);log.info(停机时间DateUtil.format(endTime,DatePattern.NORM_DATETIME_PATTERN));// 添加到系统启动日志表SysStartLogsysStartLognewSysStartLog();sysStartLog.setEndTime(endTime);sysStartLogService.saveOrUpdate(sysStartLog);// 延迟5秒关闭Spring Boot应用上下文ScheduledExecutorServiceexecutorExecutors.newSingleThreadScheduledExecutor();executor.schedule(run::close,5,TimeUnit.SECONDS);executor.shutdown();}));}优雅停机流程JVM 收到关闭信号 ↓ 触发 ShutdownHook ↓ 记录停机时间 ↓ 保存到数据库 ↓ 延迟5秒 ↓ 关闭 Spring 应用上下文四、调用方式4.1 自动触发该监听器通过Component注解自动注册到 Spring 容器在应用启动时自动执行。4.2 配置启用在配置文件中设置# 是否启用启动日志 startLog.enabledtrue六、技术要点6.1 ApplicationRunner 接口publicinterfaceApplicationRunner{voidrun(ApplicationArgumentsargs)throwsException;}特点在应用启动完成后执行可以访问启动参数执行顺序CommandLineRunner→ApplicationRunner6.2 ShutdownHookRuntime.getRuntime().addShutdownHook(newThread(()-{// 清理逻辑}));特点在 JVM 关闭前执行用于资源清理不能保证一定执行如强制 kill6.3 优雅停机ScheduledExecutorServiceexecutorExecutors.newSingleThreadScheduledExecutor();executor.schedule(run::close,5,TimeUnit.SECONDS);作用延迟关闭确保业务处理完成给予系统缓冲时间避免数据丢失七、总结ApplicationStartAndStopListener实现了以下功能启动时间记录应用启动时记录启动时间到数据库关闭时间记录应用关闭时记录关闭时间到数据库优雅停机延迟5秒关闭确保资源正确释放配置控制通过配置项控制是否启用日志记录异常容错异常不影响应用正常启动适用场景系统运行时间统计系统稳定性监控故障排查和日志分析资源清理和优雅停机