springboot项目启动成功后执行一段代码的两种方式
1.转 springboot项目启动成功后执行一段代码的两种方式
3. springboot 学习之路 9 (项目启动后就执行特定方法)
4.在项目启动之后自动执行指定方法,实现同步Redis缓存数据。
4.1 开始配置,有两种方式:ApplicationRunner和CommandLineRunner 除了可接受参数不同,其他的大同小异
4.2 ApplicationRunner】
package org.config; 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值决定,值小先执行 * * @author single-聪 * @date 2019年10月31日 * @version 0.0.1 */ @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(); } }
4.3 CommandLineRunner
package org.config; 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值决定,值小先执行 * * @author single-聪 * @date 2019年10月31日 * @version 0.0.1 */ @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(); } }
4.4 在上述两个类中PushMessageService 为自己的service接口,具体是什么随意,使用方式和controller使用一样,这样项目启动之后日志打印顺序为:
测试服务MyApplicationRunner
执行MyCommandLineRunner
4.5 更换@Order注解的value值可以自定义执行顺序(某些操作需要有先后顺序)
当项目中同时实现了ApplicationRunner和CommondLineRunner接口时,可使用Order注解或实现Ordered接口来指定执行顺序,值越小越先执行
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 百万级群聊的设计实践
· 永远不要相信用户的输入:从 SQL 注入攻防看输入验证的重要性
· 全网最简单!3分钟用满血DeepSeek R1开发一款AI智能客服,零代码轻松接入微信、公众号、小程
· .NET 10 首个预览版发布,跨平台开发与性能全面提升
· 《HelloGitHub》第 107 期