CommandLineRunner
springboot的
CommandLineRunner
接口主要用于实现应用初始化之后,去执行一段逻辑代码,并且在整个项目的声明周期中,执行一次,源码如下:
package org.springframework.boot;
public interface CommandLineRunner {
void run(String... var1) throws Exception;
}
1.两种实现方式
1.1继承CommandLineRunner接口
和注解 @Componerent一起使用,如果涉及到多个,用@Order()注解去设置执行顺序
@Component
@Order(value = 1)
public class CLR1 implements CommandLineRunner{
public void run(String... strings) throws Exception {
//do something
}
}
@Component
@Order(value = 2)
public class CLR2 implements CommandLineRunner{
public void run(String... strings) throws Exception {
//do something
}
}
1.2 和@Bean连用,返回CommandLineRunner实例
@Bean
public CommandLineRunner initialize(SomeModel ModelInstance) {
return (abc) -> {
ModelInstance.dosomething(...)
};
}
该方法需要放在有@Component/@SpringBootApplication注解的类上
abc
为任意字符,SomeModel
ModelInstance
为用Spring bean对象,controller中可用@Resource@Autowired接收
2.为什么要使用CommandLineRunner
- 实现在应用启动后,去执行相关代码逻辑,且只会执行一次
- spring batch批量处理框架依赖这些执行器去触发执行任务
- 可以使用依赖,bean对象,因为它们已经初始化好了