zoukankan      html  css  js  c++  java
  • SpringBoot的ApplicationRunner

     Article1

    在开发中可能会有这样的情景。需要在容器启动的时候执行一些内容。比如读取配置文件,数据库连接之类的。SpringBoot给我们提供了两个接口来帮助我们实现这种需求。这两个接口分别为CommandLineRunnerApplicationRunner。他们的执行时刻为容器启动完成的时候。

    这两个接口中有一个run方法,我们只需要实现这个方法即可。这两个接口的不同之处在于:ApplicationRunner中run方法的参数为ApplicationArguments,而CommandLineRunner接口中run方法的参数为String数组。目前我在项目中用的是ApplicationRunner。是这么实现的:

    package com.jdddemo.demo.controller;
     
    import org.springframework.boot.ApplicationArguments;
    import org.springframework.boot.ApplicationRunner;
    import org.springframework.stereotype.Component;
     
    @Component
    public class JDDRunner implements ApplicationRunner {
        @Override
        public void run(ApplicationArguments args) throws Exception {
            System.out.println(args);
            System.out.println("这个是测试ApplicationRunner接口");
        }
    }

     执行结果如下:

    可用于添加缓存、定时任务,也可实现某些业务逻辑(@Autowired可以注入JavaBean)


    ---------------------
    作者:姜小栀在北
    来源:CSDN
    原文:https://blog.csdn.net/jdd92/article/details/81053404

     Article2

    业务场景:
    应用服务启动时,加载一些数据和执行一些应用的初始化动作。如:删除临时文件,清除缓存信息,读取配置文件信息,数据库连接等。
    1、SpringBoot提供了CommandLineRunner和ApplicationRunner接口。当接口有多个实现类时,提供了@order注解实现自定义执行顺序,也可以实现Ordered接口来自定义顺序。
    注意:数字越小,优先级越高,也就是@Order(1)注解的类会在@Order(2)注解的类之前执行。
    两者的区别在于:
    ApplicationRunner中run方法的参数为ApplicationArguments,而CommandLineRunner接口中run方法的参数为String数组。想要更详细地获取命令行参数,那就使用ApplicationRunner接口

    ApplicationRunner

    @Component
    @Order(value = 10)
    public class AgentApplicationRun2 implements ApplicationRunner {
        @Override
        public void run(ApplicationArguments applicationArguments) throws Exception {
    
        }
    }

    CommandLineRunner

    @Component
    @Order(value = 11)
    public class AgentApplicationRun implements CommandLineRunner {
    
        @Override
        public void run(String... strings) throws Exception {
    
        }
    }

    ---------------------
    作者:小贼驴
    来源:CSDN
    原文:https://blog.csdn.net/weixin_38362455/article/details/83023025

  • 相关阅读:
    Java高级部分--工具类(1)
    Javascript 与正则表达式
    Java基础部分--面向对象基础(1)
    Java基础部分--面向对象高级特性(2)
    持久层框架--hibernate(4)
    持久层框架--hibernate(3)
    持久层框架--hibernate(2)
    python常见面试题
    单元测试之写用例(全局变量,异常处理,断言)
    jmeter安装踩坑记录
  • 原文地址:https://www.cnblogs.com/ryelqy/p/11081752.html
Copyright © 2011-2022 走看看