admin管理员组文章数量:1566684
一、作用
ApplicationRunner和CommandLineRunner都用于在容器启动后(也就是SpringApplication.run()执行结束)执行某些逻辑。
可用于项目的一些准备工作,比如加载配置文件,加载执行流,定时任务等
二、共同点和区别
共同点
- 执行时机都是在容器启动完成时进行
- 两个接口中都有一个run方法
不同点
run 方法中的参数是不一样的
CommandLineRunner 接收的参数为:name1 name2 name3 例如:
java -jar xxx.jar data1 data2 data3
在项目启动时添加参数
断点打进 CommandLineRunner,可以看到接收的参数
断点打进 ApplicationRunner,可以看到接收的参数
三、执行顺序
ApplicationRunner和CommandLineRunner 都可以有多个实现类
,怎么让多个实现类按照一定的顺序来执行
1、可以在实现类上加上@Order注解指定执行的顺序
2、可以在实现类上实现Ordered接口
【注意】 数字越小,优先级越高
四、代码实践
1、主启动类上添加注释
@Slf4j
@SpringBootApplication
public class HelloWorldApplication {
public static void main(String[] args) {
// 启动spring 应用
log.info("Spring BOOT 启动开始");
SpringApplication.run(HelloWorldApplication.class,args);
log.info("Spring BOOT 启动结束");
}
}
2、向容器中添加ApplicationRunner和CommandLineRunner的实现类
@Component
@Slf4j
public class MyApplicationRuner implements ApplicationRunner {
@Override
public void run(ApplicationArguments args) throws Exception {
log.info("ApplicationRunner=====执行开始");
log.info(args.toString());
log.info("ApplicationRunner=====执行完成");
}
}
@Component
@Slf4j
public class MyCommandLineRunner implements CommandLineRunner {
@Override
public void run(String[] args) throws Exception {
log.info("CommandLineRunner=====执行开始");
log.info(args.toString());
log.info("CommandLineRunner=====执行完毕");
}
}
【注意】可以看到在都没有标注order的情况下,ApplicationRunner 的优先级要高于CommandLineRunner
如果在组件上加了order注解,则按照注解定义的顺序执行
本文标签: 区别作用ApplicationRunnerCommandLineRunner
版权声明:本文标题:ApplicationRunner和CommandLineRunner的作用和区别 内容由热心网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:https://www.elefans.com/xitong/1726219761a1060961.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论