官网出处
https://docs.spring.io/spring-boot/docs/2.1.1.RELEASE/reference/htmlsingle/#boot-features-command-line-runner
23.8 Using the ApplicationRunner or CommandLineRunner
Both interfaces work in the same way and offer a single
run
method, which is called just beforeSpringApplication.run(…)
completes简单翻译:这两个接口的工作原理是一样的,都提供了一个run方法,这个run方法是在SpringApplication.run()方法执行之前被调用。
简单来说就是在SpringBoot启动成功之前,加载你想要加载的东西。比如一些资源的初始化等等。
代码示例
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
System.out.println("SpringBoot启动开始");
SpringApplication.run(DemoApplication.class, args);
System.out.println("SpringBoot启动结束");
}
}
@Component
class MyRunner implements CommandLineRunner{
@Override
public void run(String... args) throws Exception {
System.out.println("初始化自定义资源");
}
}
效果展示
2018-12-14 20:24:04.527 INFO 14740 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2018-12-14 20:24:04.527 INFO 14740 --- [ main] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 1453 ms
2018-12-14 20:24:04.788 INFO 14740 --- [ main] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor'
2018-12-14 20:24:04.991 INFO 14740 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
2018-12-14 20:24:04.997 INFO 14740 --- [ main] com.example.demo.DemoApplication : Started DemoApplication in 2.559 seconds (JVM running for 5.607)
初始化自定义资源
SpringBoot启动结束