SpringBoot-ApplicationRunner和CommandLineRunner的使用

官网出处

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 before SpringApplication.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启动结束

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值