🐻SpringBoot项目启动后执行方法的三种方式
使用场景:可以在程序启动时加载一些自定义的监听器之类的,例如Socket服务的监听器,此时如果使用@PostConstract,Socket服务的监听器将阻塞启动程序,导致程序不能正常启动。
方式一:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | import lombok.extern.slf4j.Slf4j; import org.springframework.context.ApplicationListener; import org.springframework.context.event.ContextRefreshedEvent; import org.springframework.stereotype.Component; /** * @author zhangzhixi * @version 1.0 * @description SpringBoot项目加载后执行,演示一:实现 ApplicationListener 接口 * @date 2023-07-17 10:26 */ @Component @Slf4j public class ProjectLoadExecuteDemo1 implements ApplicationListener<ContextRefreshedEvent> { @Override public void onApplicationEvent(ContextRefreshedEvent event) { if (event.getApplicationContext().getParent() == null ) { log.info( "SpringBoot项目加载后执行,演示一:实现 ApplicationListener 接口" ); } } } |
方式二:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | import lombok.extern.slf4j.Slf4j; import org.springframework.boot.ApplicationArguments; import org.springframework.boot.ApplicationRunner; import org.springframework.context.ApplicationListener; import org.springframework.context.event.ContextRefreshedEvent; import org.springframework.stereotype.Component; /** * @author zhangzhixi * @version 1.0 * @description SpringBoot项目加载后执行,演示二:实现 ApplicationRunner 接口 * @date 2023-07-17 10:26 */ @Component @Slf4j public class ProjectLoadExecuteDemo2 implements ApplicationRunner { @Override public void run(ApplicationArguments args) throws Exception { log.info( "SpringBoot项目加载后执行,演示二:实现 ApplicationRunner 接口" ); } } |
方式三:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | import lombok.extern.slf4j.Slf4j; import org.springframework.boot.CommandLineRunner; import org.springframework.stereotype.Component; /** * @author zhangzhixi * @version 1.0 * @description SpringBoot项目加载后执行,演示三:实现 ApplicationRunner 接口 * @date 2023-07-17 10:26 */ @Component @Slf4j public class ProjectLoadExecuteDemo3 implements CommandLineRunner { @Override public void run(String... args) throws Exception { log.info( "SpringBoot项目加载后执行,演示三:实现 CommandLineRunner 接口" ); } } |
分类:
微服务框架
标签:
SpringBoot
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?