方式一、编写一个类实现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) 我也随着项目启动而启动啦 我会在项目启动的时候运行