SpringBoot项目启动后执行某个方法的方式(开机启动)
springboot项目启动自动触发方法场景:
做这个的原因:前端数据一直在变化,导致我每次打包之后需要清缓存处理缓存数据,故而有了本文,在项目启动之后自动执行指定方法,本文作用是实现同步缓存数据。
开始配置,有两种方式:ApplicationRunner和CommandLineRunner
实现ApplicationRunner接口
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | import org.service.PushMessageService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.ApplicationArguments; import org.springframework.boot.ApplicationRunner; import org.springframework.core.annotation.Order; import org.springframework.stereotype.Component; import lombok.extern.slf4j.Slf4j; /** * 实现ApplicationRunner接口,执行顺序按照value值决定,值小先执行 */ @Slf4j @Component @Order (value = 1 ) public class MyApplicationRunner implements ApplicationRunner { @Autowired private PushMessageService pushMessageService; @Override public void run(ApplicationArguments args) throws Exception { log.info( "测试服务MyApplicationRunner" ); pushMessageService.resetRedis(); } } |
实现CommandLineRunner接口
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | import org.service.PushMessageService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.core.annotation.Order; import org.springframework.stereotype.Component; import lombok.extern.slf4j.Slf4j; /** * 实现MyCommandLineRunner接口,执行顺序按照value值决定,值小先执行 */ @Slf4j @Component @Order (value = 2 ) public class MyCommandLineRunner implements CommandLineRunner { @Autowired private PushMessageService pushMessageService; @Override public void run(String... args) throws Exception { log.info( "执行MyCommandLineRunner" ); // 同步缓存中的通知消息数目 pushMessageService.resetRedis(); } } |
@Component注解相应的类,并重写run方法,若存在多个启动执行的任务,可利用在类上使用@Order注解来指定顺序。
在上述两个类中PushMessageService 为自己的service接口,具体是什么随意,使用方式和controller使用一样,这样项目启动之后日志打印顺序为:
1 2 | 测试服务MyApplicationRunner 执行MyCommandLineRunner |
now ,fight for future
分类:
SpringBoot
标签:
SpringBoot
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· Vue3状态管理终极指南:Pinia保姆级教程