美文网首页
SpringBoot 启动初始化

SpringBoot 启动初始化

作者: 编程喵喵 | 来源:发表于2019-08-18 22:15 被阅读0次

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);
    }
}

相关文章

网友评论

      本文标题:SpringBoot 启动初始化

      本文链接:https://www.haomeiwen.com/subject/liqdsctx.html