在使用SpringBoot构建项目时,我们通常有一些预先数据加载,数据处理等操作需要在项目启动后执行, SpringBoot提供了一个简单的方式来实现–CommandLineRunner,源码超简单:
/**
* Interface used to indicate that a bean should <em>run</em> when it is contained within
* a {@link SpringApplication}. Multiple {@link CommandLineRunner} beans can be defined
* within the same application context and can be ordered using the {@link Ordered}
* interface or {@link Order @Order} annotation.
* <p>
* If you need access to {@link ApplicationArguments} instead of the raw String array
* consider using {@link ApplicationRunner}.
*
* @author Dave Syer
* @since 1.0.0
* @see ApplicationRunner
*/
@FunctionalInterface
public interface CommandLineRunner {
/**
* Callback used to run the bean.
* @param args incoming main method arguments
* @throws Exception on error
*/
void run(String... args) throws Exception;
}
我们需要时只需实现CommandLineRunner接口重写run方法即可.那如果有多个类继承了这个接口,可以通过@Order(value = x)来排序,按照value的大小,数值小的先执行的规则顺序执行每个实现类
一个小Demo
一个实现CommandLineRunner的类
@Component
@Slf4j
@Order(value = 1)
public class RunnerTest1 implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
log.info("RunnerTest1 --> run run1");
}
}
另一个实现CommandLineRunner的类
@Component
@Slf4j
@Order(value = 2)
public class RunnerTest2 implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
log.info("RunnerTest2 --> run run2");
}
}
主方法
@SpringBootApplication
@Slf4j
public class XiaoLearnSpringApplication {
public static void main(String[] args) {
SpringApplication.run(XiaoLearnSpringApplication.class, args);
}
}
启动!
可以通过清晰地看到,在启动后顺序地执行了Demo的两个run方法
嗯, 狗子感觉是个很好用的接口呢
欢迎关注~~~~~~~~~~~~