文章目录
CommandLineRunner接口介绍
CommandLineRunner接口是在容器启动成功后的最后一步回调(类似开机自启动)。
1. CommandLineRunner接口使用
- 写一个类,实现CommandLineRunner接口,将该类注入到Spring容器中;
- 可以通过@Order注解(属性指定数字越小表示优先级越高)或者Ordered接口来控制执行顺序。
例如,我们自定义两个类,实现CommandLineRunner接口,实现run方法,在run方法中添加处理逻辑。
@Order(5)
@Component
public class AppStartReport implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
System.out.println("AppStartReport : 项目成功启动------------------");
}
}
@Order(2)
@Component
public class AppStartReport2 implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
System.out.println("AppStartReport2 : 项目成功启动------------------");
}
}
项目启动效果如下,AppStartReport2 较AppStartReport 先执行: