SpringBoot 启动初始化

ApplicationRunner与CommandLineRunner

如果需要在SpringApplication启动时执行一些特殊的代码 ,你可以实现ApplicationRunnerCommandLineRunner接口, 这两个接口工作方式相同,都只提供单一的run方法,而且该方法仅在SpringApplication.run(…)完成之前调用,更准确的说是在构造SpringApplication实例完成之后调用run()的时候,具体分析见后文 ,所以这里将他们分为一类。

ApplicationRunner

构造一个类实现ApplicationRunner接口

@Component
@Order(value = 10)
public class AgentApplicationRun2 implements ApplicationRunner {
    @Override
    public void run(ApplicationArguments applicationArguments) throws Exception {
    }

CommandLineRunner

对于这两个接口而言,我们可以通过Order注解来指定调用顺序, @Order() 中的值越小,优先级越高

@Component
@Order(value = 11)
public class AgentApplicationRun implements CommandLineRunner {

    @Override
    public void run(String... strings) throws Exception {

    }
}

两者区别联系

  • 当然我们也可以同时使用ApplicationRunnerCommandLineRunner,默认情况下前者比后者先执行,但是这没有必要,使用一个就好了
  • ApplicationRunnerrun方法的参数为ApplicationArguments而CommandLineRunner接口中run方法的参数为String数组。想要更详细地获取命令行参数,那就使用ApplicationRunner接口

例子

@Component
public class ExcelRunner implements CommandLineRunner {

    @Autowired
    DependencyService dependencyService;

    public void run(String... args) throws Exception {
        dependencyService.clear();
        System.out.println("Excel 数据读取 ...");
        List<Dependency> dependencyList = ExcelUtil.readExcelFile();
        dependencyService.save(dependencyList);
    }
}
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容