业务场景
在业务场景中,有些情况下需要我们一启动项目就执行一些操作.
例如数据配置的相关初始化,通用缓存的数据构造等。
springboot为我们提供了commandlinerunner和applicationrunner两个接口来实现这个功能。
接口说明
commandlinerunner和applicationrunner两个接口除了参数不同,其他基本相同,可以根据实际需求选择使用.
commandlinerunner中的run方法参数为string..., applicationrunner中的run方法参数为applicationarguments.
在同等顺序中,applicationrunner会比commandlinerunner优先执行
使用方法
定义一个类实现该接口,重写其中的run方法即可. 如果有多个实现类,我们可以通过@order注解来定义优先级(数字越低越先执行)
@order(1) @component public class mycommandlinerunner1 implements commandlinerunner { @override public void run(string... args) throws exception { system.out.println("========== 初始任务mycommandlinerunner1 =========="); } } @order(2) @component public class mycommandlinerunner2 implements commandlinerunner { @override public void run(string... args) throws exception { system.out.println("========== 初始任务mycommandlinerunner2 =========="); // throw new runtimeexception("模拟异常"); } } @order(2) @component public class myapplicationrunner1 implements applicationrunner { @override public void run(applicationarguments args) throws exception { system.out.println("========== 初始任务myapplicationrunner1 =========="); } }
启动项目, 输出如下:
注意事项
1. commandlinerunner和applicationrunner的执行其实是整个项目启动周期中的一部分,runner执行完成后,才最终启动项目.
2. 如果runner中出现异常, 就会影响项目的启动,所以要在runner中处理异常
3. 如果runner中需要指定定时周期任务(如一直循环打印某些信息等),需要在异步线程中执行,否则项目的主线程会一直阻塞,无法启动成功
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。
发表评论