[SpringBoot]springboot -项目启动完成之后,执行特定方法

有时候项目会有这样的需求:在 springboot 项目启动完成之后,需要加载一些数据

最先想到的方法就是通过 ApplicationRunner 去做:

@Component
public class TestApplicationRunner implements ApplicationRunner {
    @Override
    public void run(ApplicationArguments args) throws Exception {
        System.out.println("TestApplicationRunner method will be execute when the project started");
    }
}

除了 ApplicationRunner 这种方式去做之外,还可以通过 CommandLineRunner 去做:

@Component
public class TestCommandLineRunner implements CommandLineRunner {
    @Override
    public void run(String... args) throws Exception {
        System.out.println("TestCommandLineRunner method will be execute when the project started");
    }
}

在这里插入图片描述

上图是写了之后的运行效果图,应该可以看到,在项目启动成功之后,我们在 ApplicationRunnerCommandLineRunner 中的内容就运行了,而且执行顺序上, ApplicationRunner 要比 CommandLineRunner 先执行

这篇文章就先简单介绍一下 springboot 项目启动完成之后,如何执行特定方法,我在项目中用的第一种方式去实现的
如果想要让多个方法按照顺序执行,可以试下 @Order 实现方式:

@Component
public class TestApplicationRunnerByOrder implements ApplicationRunner, Ordered {
    @Override
    public void run(ApplicationArguments args) throws Exception {
        System.out.println("TestApplicationRunnerByOrder method will be execute when the project started");
    }

    @Override
    public int getOrder() {
        // 通过设置这里的数字来指定执行顺序
        return 0;
    }
}


@Component
public class TestApplicationRunner implements ApplicationRunner {
    @Override
    public void run(ApplicationArguments args) throws Exception {
        System.out.println("TestApplicationRunner method will be execute when the project started");
    }
}

如果是上面的代码的话,运行之后,程序执行结果是这样的:
在这里插入图片描述
如果我们在 TestApplicationRunner 方法上,加上 @Order(value = 0) 注解:

@Component
@Order(value = 0)
public class TestApplicationRunner implements ApplicationRunner {
    @Override
    public void run(ApplicationArguments args) throws Exception {
        System.out.println("TestApplicationRunner method will be execute when the project started");
    }
}

接下来运行,就能看到执行顺序相比于刚刚,发生了变化:
在这里插入图片描述

以上,感谢您的阅读哇~

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值