ApplicationRunner和CommandLineRunner
项目中需要用到服务启动成功以后调用一个方法把配置项刷进缓存
ApplicationRunner
@Component
public class ApplicationRunnerImpl implements ApplicationRunner {
@Override
public void run(ApplicationArguments args) throws Exception {
String[] sourceArgs = args.getSourceArgs();
for (String arg : sourceArgs) {
System.out.print(arg + " ");
}
System.out.println();
}
}
CommandLineRunner
@Component
public class CommandLineRunnerImpl implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
for (String arg : args) {
System.out.print(arg + " ");
}
System.out.println();
}
}
指定执行顺序
当项目中同时实现了ApplicationRunner和CommondLineRunner接口时,可使用Order注解或实现Ordered接口来指定执行顺序,值越小越先执行
区别
二者的功能和官方文档一模一样,都是在Spring容器初始化完毕之后执行起run方法
不同点在于,前者的run方法参数是String...args,直接传入字符串
后者的参数是ApplicationArguments,对参数进行了封装
不积跬步,无以至千里;不积小流,无以成江海
浙公网安备 33010602011771号