CommandLineRunner的主要作用是在项目启动时初始化某些资源。
那么spring boot是怎么做到的?在启动时初始化,那么目标直接定位在spring boot启动类中的代码,所以先跟进spring boot启动类,启动代码如下:
SpringApplication.run(Application.class, args);
跟进run方法中,会看到一个callRunners方法,如下:
跟进callRunners方法中,方法如下:
private void callRunners(ApplicationContext context, ApplicationArguments args) {
List
可以发现排序后,最后会遍历,调用callRunner方法,跟进callRunner方法,如下:
private void callRunner(CommandLineRunner runner, ApplicationArguments args) {
try {
runner.run(args.getSourceArgs());
} catch (Exception var4) {
throw new IllegalStateException("Failed to execute CommandLineRunner", var4);
}
}
会发现这里的runner.run方法,其实就是CommandLineRunner对象在调用自身的run方法,因此就会执行到我们自定义的CommandLineRunner子类中的初始化逻辑。
根据以上思路打上断点,即可验证以上的分析是否正确了。



