• Spring Boot中 CommandLineRunner 与 ApplicationRunner作用、区别


    CommandLineRunner 和 ApplicationRunner 是 Spring Boot 提供的两种用于在应用程序启动后执行初始化代码的机制。这两种接口允许你在 Spring 应用上下文完全启动后执行一些自定义的代码,通常用于执行一次性初始化任务,如数据库预填充、缓存预热等。

    CommandLineRunner

    CommandLineRunner 是一个简单的接口,它只有一个方法:

    1. public interface CommandLineRunner {
    2. void run(String... args) throws Exception;
    3. }

    此接口的 run 方法接受一个字符串数组参数,代表命令行参数。这意味着你可以访问应用启动时传递给它的参数。如果实现 CommandLineRunner 接口的类被 Spring 扫描到,那么它的 run 方法将在应用启动完成且所有单例 Bean 被创建之后执行。

    ApplicationRunner

    ApplicationRunner 类似于 CommandLineRunner,但它提供了更丰富的功能,特别是它允许你访问 ApplicationArguments 对象:

    1. public interface ApplicationRunner {
    2. void run(ApplicationArguments args) throws Exception;
    3. }

    ApplicationArguments 提供了对命令行参数的更高级访问,它能够区分选项和非选项参数,并能判断参数是否包含非选项参数。这对于需要处理复杂命令行参数的应用非常有用。

    区别

    主要的区别在于 ApplicationRunner 提供了对命令行参数的更精细控制,而 CommandLineRunner 则直接提供一个字符串数组。

    执行顺序

    如果存在多个 CommandLineRunner 或 ApplicationRunner 的实现,它们将按照 Bean 的定义顺序执行。如果需要自定义执行顺序,可以实现 Ordered 接口或使用 @Order 注解。

    示例

    这里是一个使用 CommandLineRunner 的示例:

    1. @Component
    2. public class MyCommandLineRunner implements CommandLineRunner {
    3. @Override
    4. public void run(String... args) throws Exception {
    5. System.out.println("CommandLineRunner is running...");
    6. }
    7. }

    这里是一个使用 ApplicationRunner 的示例:

    1. @Component
    2. public class MyApplicationRunner implements ApplicationRunner {
    3. @Override
    4. public void run(ApplicationArguments args) throws Exception {
    5. System.out.println("ApplicationRunner is running...");
    6. if (args.containsOption("debug")) {
    7. System.out.println("Debug mode is enabled.");
    8. }
    9. }
    10. }

    示例执行结果

    两者都是在 Spring Boot 应用启动完成后执行的,可以用来执行必要的初始化任务。

  • 相关阅读:
    router-link 和 router-view的区别
    用loadrunner监视远程服务器的方法
    Fabric.js+vue 实现鼠标滚轮缩放画布+移动画布
    Android-Jetpack Compose的简单运用
    SQL库的相关操作
    回归预测 | MATLAB实现RBF径向基神经网络多输入多输出预测
    关于TreeView的简单使用(Qt6.4.1)
    运维排查 | Systemd 之服务停止后状态为 failed
    vue父子组件传递参数详解
    java基础---static,多态,抽象类,接口,匿名内部类
  • 原文地址:https://blog.csdn.net/weixin_44029753/article/details/140055059