• springboot实现项目启动前的一些操作


    在服务启动时,做一些操作,比如加载配置,初始化数据,请求其他服务的接口等。
    有三种方法:

    • 第一种是实现CommandLineRunner接口
    • 第二种是实现ApplicationRunner接口
    • 第三种是使用注解:@PostConstruct

    三者使用方法

    先看下三种方法分别怎么实现我们的目的

    CommandLineRunner

    CommandLineRunner执行的时间节点是在Application完成初始化工作之后。

    CommandLineRunner在有多个实现的时候,可以使用@order注解指定执行先后顺序。、

    使用方法:实现CommandLineRunner接口,并重写run方法,run方法里写我们的初始化操作。

    示例:

    import org.springframework.boot.CommandLineRunner;
    import org.springframework.stereotype.Component;
    
    
    @Component
    public class InitTest02 implements CommandLineRunner {
        @Override
        public void run(String... args) throws Exception {
            System.out.println("========CommandLineRunner");
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    ApplicationRunner

    ApplicationRunner跟CommandLineRunner是区别是在run方法里接收的参数不同,CommandLineRuner接收的参数是String… args,而ApplicationRunner的run方法的参数是ApplicationArguments 。

    实现ApplicationRunner接口,并重写run方法,run方法里写我们的初始化操作。

    示例:

    import org.springframework.boot.ApplicationArguments;
    import org.springframework.boot.ApplicationRunner;
    import org.springframework.stereotype.Component;
    
    
    @Component
    public class InitTest01 implements ApplicationRunner {
        @Override
        public void run(ApplicationArguments args) throws Exception {
            System.out.println("=======ApplicationRunner");
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    @PostConstruct

    @PostConstruct是在对象加载完之后执行。

    使用@PostConstruct注解再自己写的方法上,方法内写初始化逻辑

    示例:

    import org.springframework.stereotype.Component;
    
    import javax.annotation.PostConstruct;
    
    
    @Component
    public class InitTest03 {
    
        @PostConstruct
        public void start() {
            System.out.println("========PostConstruct");
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    三者区别

    三者都可以实现项目启动前的一些初始化操作,唯一不同的是初始化的时间不同。

    Spring应用启动过程中,肯定是要自动扫描有@Component注解的类,加载类并初始化对象进行自动注入。加载类时首先要执行static静态代码块中的代码,之后再初始化对象时会执行构造方法。

    在对象注入完成后,调用带有@PostConstruct注解的方法。当容器启动成功后,再根据@Order注解的顺序调用CommandLineRunner和ApplicationRunner接口类中的run方法。

    因此,加载顺序为static>constructer>@PostConstruct>CommandLineRunner和ApplicationRunner。

    参考

    https://blog.csdn.net/qinshengfei/article/details/114856010

  • 相关阅读:
    大模型(e.g., ChatGPT)里面的一些技术和发展方向
    SpringCloudalibaba2
    授予渔,从0开始搭建一个自己想要的网页
    都2023年了,你必须知道的几款主流性能测试工具!
    vue中父组件给子组件传递了参数后,什么时候确保子组件中收到的参数更新了
    Facebook、亚马逊养号选择什么代理IP?
    MyBatis-Plus实现SQL执行前统一处理添加只读标识等注释
    负载均衡的算法(静态算法与动态算法)
    技术分享 | app自动化测试(Android)-- 特殊控件 Toast 识别
    MySQL启动不了,无法启动MySQL服务解决技巧
  • 原文地址:https://blog.csdn.net/qq_43745578/article/details/126918750