Spring Boot 2 (七):Spring Boot 如何解决项目启动时初始化资源

本文介绍了如何利用Spring Boot的CommandLineRunner接口在项目启动时进行资源初始化,例如线程池和证书加载。CommandLineRunner组件在所有Spring Beans初始化后,SpringApplication.run()之前执行,适合用于数据初始化。文章通过实例展示了如何创建和配置CommandLineRunner,以及如何通过@Order注解控制执行顺序。此外,提到了ApplicationRunner作为另一种选择,与CommandLineRunner效果相似。
摘要由CSDN通过智能技术生成

在我们实际工作中,总会遇到这样需求,在项目启动的时候需要做一些初始化的操作,比如初始化线程池,提前加载好加密证书等。今天就给大家介绍一个 Spring Boot 神器,专门帮助大家解决项目启动初始化资源操作。

这个神器就是 CommandLineRunner,CommandLineRunner 接口的 Component 会在所有 Spring Beans 都初始化之后,SpringApplication.run() 之前执行,非常适合在应用程序启动之初进行一些数据初始化的工作。

接下来我们就运用案例测试它如何使用,在测试之前在启动类加两行打印提示,方便我们识别 CommandLineRunner 的执行时机。

@SpringBootApplication
public class CommandLineRunnerApplication {
   
	public static void main(String[] args) {
   
		System.out.println("The service to start.");
		SpringApplication.run(CommandLineRunnerApplication.class, args);
		System.out.println("The service has started.");
	}
}

接下来我们直接创建一个类继承 CommandLineRunner ,并实现它的 run() 方法。

@Component
public class Runner implements CommandLineRunner {
   
    @Override
    public void run(String... args) throws Exception {
   
        System.out.println("The Runner start to initialize ...");
    }
}

我们在 run() 方法中打印了一些参数来看出它的执行时机。完成之后启动项目进行测试:

...
The service to start.

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值