• CommandLineRunner和ApplicationRunner


    使用场景

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

    不同点

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

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

    官方说明:

    • 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. 

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

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

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

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

  • 相关阅读:
    OpenCV 之 图像平滑
    C++11 之 nullptr
    C++11 之 scoped enum
    C++ 之 常量成员函数
    德国的挑战
    OpenCV 之 直方图处理
    OpenCV 之 霍夫变换
    排序算法之——归并排序(两种方法及其优化)
    排序算法之——快速排序(剖析)
    排序算法之——桶排序
  • 原文地址:https://www.cnblogs.com/tonyq/p/9003130.html
Copyright © 2020-2023  润新知