ApplicationRunner
和CommandLineRunner
的作用是在 SpringBootApplication 环境加载完成后且正式运行前执行指定任务。
自定义三个配置类:
ConfigA
实现ApplicationRunner
接口,在run
方法中添加日志打印
package com.example.demo;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.annotation.Configuration;
@Configuration
public class ConfigA implements ApplicationRunner {
@Override
public void run(ApplicationArguments args) throws Exception {
System.out.println("Config implements ApplicationRunner");
}
}
ConfigB
实现CommandLineRunner
接口,在run
方法中添加日志打印
package com.example.demo;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Configuration;
@Configuration
public class ConfigB implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
System.out.println("Config implements CommandLineRunner");
}
}
ConfigC
为普通的配置类,在构造函数中添加日志打印
package com.example.demo;
import org.springframework.context.annotation.Configuration;
@Configuration
public class ConfigC {
public ConfigC() {
System.out.println("Normal Config");
}
}
启动应用,日志输出如下:
2021-12-07 17:13:16.512 INFO 9164 --- [ main] com.example.demo.DemoApplication : Starting DemoApplication using Java 17.0.1 on DESKTOP with PID 9164 ([D:\learn\Spring\demo\target\classes]() started by ... in [d:\learn\Spring\demo]())
2021-12-07 17:13:16.514 INFO 9164 --- [ main] com.example.demo.DemoApplication : No active profile set, falling back to default profiles: default
Normal Config
2021-12-07 17:13:16.953 INFO 9164 --- [ main] com.example.demo.DemoApplication : Started DemoApplication in 0.764 seconds (JVM running for 1.184)
Config implements ApplicationRunner
Config implements CommandLineRunner
从日志中可以看出,ApplicationRunner
和CommandLineRunner
的run
方法在SpringBootApplication启动成功后执行。
注意:ApplicationRunner
和CommandLineRunner
的run
方法执行顺序可以通过@Order
注解或Ordered
接口控制。