实现SpringBoot应用启动时运行特定代码


前言

在SpringBoot应用启动的时候一般都会初始化一些数据到应用中,这时就要运行一些特定的代码,可以通过实现ApplicationRunner或CommandLineRunner接口,重写接口的run方法,来达到这样的效果


一、实现ApplicationRunner接口

实现代码为:

@Component
public class InitInfo implements ApplicationRunner {
    @Override
    public void run(ApplicationArguments args) throws Exception {
        System.out.println("This is an init information");
    }
}

注意:这里要把实现类加入到IOC容器中,不然SpringBoot没法识别,也不会执行run方法里面打的代码

二、实现CommandLineRunner接口

实现代码为:

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

总结

在SpringBoot应用启动的时候,想要执行我们指定的代码片段,可以通过实现ApplicationRunner或CommandLineRunner接口,重写唯一的run方法,以达到目的。需要特别注意的是:需要把实现类加入到IOC容器中,交给SpringBoot管理,这样SpringBoot才能够帮我们自动执行。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值