2020-01-06 SpringBoot之ApplicationRunner

ApplicationRunner

在项目中,可能会遇到这样一个问题:在项目启动完成之后,紧接着执行一段代码。
在SpringBoot中,提供了一个接口:ApplicationRunner。
该接口中,只有一个run方法,他执行的时机是:spring容器启动完成之后,就会紧接着执行这个接口实现类的run方法。

@Component
public class TestApplicationRunner implements ApplicationRunner{

    @Override
    public void run(ApplicationArguments applicationArguments) throws Exception {
        //do something
    }
}

说明:

1、这个实现类,要注入到spring容器中,这里使用了@Component注解;
2、在同一个项目中,可以定义多个ApplicationRunner的实现类,他们的执行顺序通过注解@Order注解或者再实现Ordered接口来实现。
3、run方法的参数:ApplicationArguments可以获取到当前项目执行的命令参数。(比如把这个项目打成jar执行的时候,带的参数可以通过ApplicationArguments获取到);
4、由于该方法是在容器启动完成之后,才执行的,所以,这里可以从spring容器中拿到其他已经注入的bean。

CommandLineRunner

CommandLineRunner接口的使用方式与ApplicationRunner接口基本相似,不同的只是run方法的参数类型,CommandLineRunner是基本类型,而ApplicationRunner是ApplicationArguments对象类型,经过一次简单封装,用户可对参数进行更多操作

@Component
public class TestCommandLineRunner implements CommandLineRunner {
 
    @Override
    // 实现该接口之后,实现其run方法,可以在run方法中自定义实现任务
    public void run(String... args) throws Exception {
        //do something
    }
}

你可能感兴趣的:(2020-01-06 SpringBoot之ApplicationRunner)