springboot系列文章之启动时初始化数据

前言

在我们用springboot搭建项目的时候,有时候会碰到在项目启动时初始化一些操作的需求,针对这种需求springboot(spring)为我们提供了以下几种方案供我们选择: 
- ApplicationRunner与CommandLineRunner接口 
- Spring Bean初始化的InitializingBean,init-method和PostConstruct 
- Spring的事件机制

ApplicationRunner与CommandLineRunner

如果需要在SpringApplication启动时执行一些特殊的代码,你可以实现ApplicationRunner或CommandLineRunner接口,这两个接口工作方式相同,都只提供单一的run方法,而且该方法仅在SpringApplication.run(…)完成之前调用,更准确的说是在构造SpringApplication实例完成之后调用run()的时候,具体分析见后文,所以这里将他们分为一类。

(1)ApplicationRunner
构造一个类实现ApplicationRunner接口

@Component
public class ApplicationRunnerTest implements ApplicationRunner {

    @Override
    public void run(ApplicationArguments args) throws Exception {
        System.out.println("ApplicationRunner");
    }
}


项目启动测试结果如图: 


(2)CommandLineRunner
对于这两个接口而言,我们可以通过Order注解或者使用Ordered接口来指定调用顺序,@Order()中的值越小,优先级越高

@Component
@Order(1)
public class CommandLineRunnerTest implements CommandLineRunner {

    @Override
    public void run(String... args) throws Exception {
        System.out.println("CommandLineRunner...");
    }
}


当然我们也可以同时使用ApplicationRunner和CommandLineRunner,默认情况下前者比后者先执行,但是这没有必要,使用一个就好了
 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值