Spring Boot之CommandLineRunner和ApplicationRunner

1,使用场景:

       我们在开发过程中会有这样的场景:需要在容器启动的时候执行一些内容,比如:读取配置文件信息,数据库连接,删除临时文件,清除缓存信息,在Spring框架下是通过ApplicationListener监听器来实现的。在Spring Boot中给我们提供了两个接口来帮助我们实现这样的需求。这两个接口就是我们今天要讲的CommandLineRunnerApplicationRunner他们的执行时机为容器启动完成的时候

2,共同点和区别:

共同点:其一执行时机都是在容器启动完成的时候进行执行;其二这两个接口中都有一个run()方法;

不同点:ApplicationRunner中run方法的参数ApplicationArguments,而CommandLineRunner接口中run方法的参数String数组


3,CommandLineRunner使用例子;

       CommandLineRunner例子大体的思路是:编写一个class,然后实现CommandLineRunner接口,最后添加@Component注解,具体代码如下:

@Component
public class MyStartupRunner1 implements CommandLineRunner{

    @Override
    public void run(String... args) throws Exception {
        System.out.println("<<<<<<<<<<<<这个是测试CommandLineRunn接口>>>>>>>>>>>>>>");
    }
}

4,ApplicationRunner使用例子;

       ApplicationRunner例子大体的思路是:编写一个class,然后实现ApplicationRunner接口,最后添加@Component注解,具体代码如下:

@Component
public class MyStartupRunner2 implements ApplicationRunner{

    @Override
    public void run(ApplicationArguments args) throws Exception {
        System.out.println("<<<<<<<<<<<<这个是测试ApplicationRunner接口>>>>>>>>>>>>>>");
    }
}

5,使用Ordered接口或者Order注解修改执行顺序;

问题提出:如果有多个实现类,而我们需要按照一定的顺序执行的话,那么应该怎么办呢?

解决方案:其一可以在实现类上加上@Order注解指定执行的顺序;其二可以在实现类上实现Ordered接口来标识。

需要注意:数字越小,优先级越高,也就是@Order(1)注解的类会在@Order(2)注解的类之前执行。 


6,再次理解共同点和区别以及使用时机;

在之前谈过的区别就不说了,我们看看官方文档对CommandLineRunner和ApplicationRunner的区别说明:

Interface used to indicate that a bean should run when it is contained within   
a SpringApplication. Multiple CommandLineRunner beans can be defined   
within the same application context and can be ordered using the Ordered   
interface or @Order annotation.   
If you need access to ApplicationArguments instead of the raw String array consider using ApplicationRunner. 

其实没有很大区别,如果想要更详细地获取命令行参数,那就使用ApplicationRunner接口。

 


来源于:

https://blog.csdn.net/gebitan505/article/details/55047819

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值