SpringBoot启动期间执行任务 --->启动期间自动执行
方式一、编写一个类实现CommandLineRunner
接口
@Commponent
public class MyRunner implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
System.out.println("我会在项目启动的时候运行");
}
}
方式二、编写一个类实现ApplicationRunner
接口
@Component
public class MyRunner2 implements ApplicationRunner {
@Override
public void run(ApplicationArguments args) throws Exception {
System.out.println("我也随着项目启动而启动啦");
}
}
结果:
2022-06-18 10:30:43.899 INFO 9560 --- [ main] com.lili.TestCsdnApplication : Starting TestCsdnApplication using Java 1.8.0_151 on DESKTOP-GEUFILT with PID 9560 (D:\studySpace\idea_workspace4\testCsdn\target\classes started by YLi_Jing in D:\studySpace\idea_workspace4\testCsdn)
2022-06-18 10:30:43.903 INFO 9560 --- [ main] com.lili.TestCsdnApplication : No active profile set, falling back to 1 default profile: "default"
2022-06-18 10:30:44.638 INFO 9560 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2022-06-18 10:30:44.645 INFO 9560 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2022-06-18 10:30:44.645 INFO 9560 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.63]
2022-06-18 10:30:44.761 INFO 9560 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2022-06-18 10:30:44.761 INFO 9560 --- [ main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 809 ms
2022-06-18 10:30:45.038 INFO 9560 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
2022-06-18 10:30:45.046 INFO 9560 --- [ main] com.lili.TestCsdnApplication : Started TestCsdnApplication in 1.503 seconds (JVM running for 2.374)
我也随着项目启动而启动啦
我会在项目启动的时候运行
标签:
java
, spring boot
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!