ApplicationRunner和CommandLineRunner

ApplicationRunner和CommandLineRunner



1.CommandLineRunner与ApplicationRunner接口作用 类似

@PostContruct

希望在项目启动完成之前,能够初始化一些操作,针对这种需求,可以考虑实现如下两个接口

笔记插图(第 1 页)

笔记插图(第 1 页)

笔记插图(第 2 页)

注:CommandLineRunner、ApplicationRunner 接口是在容器启动成功后的最后一步回调(类似开机自启动)。

接口被用作将其加入spring容器中时执行其run方法。多个

CommandLineRunner可以被同时执行在同一个spring上下文中并且执行

顺序是以order注解的参数顺序一致。

如果你需要访问ApplicationArguments去替换掉字符串数组,可以考虑使

用ApplicationRunner类。

发现二者的官方javadoc一样,区别在于接收的参数不一样。

CommandLineRunner的参数是最原始的参数,没有做任何处理。

ApplicationRunner的参数是ApplicationArguments,是对原始参数做了

进一步的封装。

ApplicationArguments是对参数(main方法)做了进一步的处理,

可以解析–name=value的,我们就可以通过name来获取value(而

CommandLineRunner只是获取–name=value)