CommandLineRunner - Spring Boot应用程序启动后执行

发布时间 2023-09-14 11:27:53作者: r1-12king

在springboot启动的时候,有的时候需要做一些初始化或者预加载的事情。

springboot给我们提供了这样一个接口

CommandLineRunner

CommandLineRunner是一个接口,用于在Spring Boot应用程序启动后执行一些特定的任务或代码块。当应用程序启动完成后,Spring Boot会查找并执行实现了CommandLineRunner接口的Bean。

说白了,就是SpringBoot启动后,我立马想干的事,都可以往里写。

 

例如:

 

@Service
public class TestService {
   public void test() {
      System.out.println("Hello world");
   }
}

 

在启动类上,加上这么个玩意:

@SpringBootApplication
public class ErrorSpringApplication {

    public static void main(String[] args) {
        SpringApplication.run(ErrorSpringApplication.class, args);
    }

    @Bean
    CommandLineRunner lookupTestService(TestService testService) {
        return args -> {
            // 1、test接口
            testService.test();

        };
    }
}

 

启动一下:

2023-09-14 11:17:22.337  INFO 44263 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
2023-09-14 11:17:22.346  INFO 44263 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2023-09-14 11:17:22.346  INFO 44263 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.78]
2023-09-14 11:17:22.478  INFO 44263 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2023-09-14 11:17:22.478  INFO 44263 --- [           main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 942 ms
2023-09-14 11:17:22.858  INFO 44263 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
2023-09-14 11:17:22.868  INFO 44263 --- [           main] c.e.error_spring.ErrorSpringApplication  : Started ErrorSpringApplication in 1.812 seconds (JVM running for 3.649)
Hello world

可以发现,SpringBoot启动后,自动加载了service的执行程序。

 

可以用来干啥:

1)代码调试

感觉偶尔还挺方便

2)、缓存预热

CommandLineRunner在应用程序启动后预热缓存,加载常用的数据到缓存中,提高应用程序的响应速度。

3)、任务初始化

使用CommandLineRunner来初始化和配置某些定时任务,确保它们在应用程序启动后立即开始运行。