Springboot-CommandLineRunner使用

943 阅读1分钟

介绍

CommandLineRunner接口 的Component 会在所有的Spring Beans 都初始化之后,SpringApplication.run() 之前执行,适合应用程序启动之初的数据初始化工作。

因此在使用SpringBoot构建项目时,我们通常有一些预先数据的加载。那么SpringBoot提供了一个简单的方式来实现–CommandLineRunner。

@Component
public class NettyServerRunner implements CommandLineRunner {

    @Override
    public void run(String... args) throws Exception {
        System.out.println(">>>>>>>>>>>>>>>NettyServerRunner tcp服务启动执行,执行加载数据等操作 <<<<<<<<<<<<<");
    }
}

自定义多数据源的加载顺序

CommandLineRunner是一个接口,我们需要时,只需实现该接口就行。如果存在多个加载的数据,我们也可以使用@Order注解来排序。