zoukankan      html  css  js  c++  java
  • Spring Boot启动时执行初始化操作三种方法分享

    @PostConstruct
    对于注入到Spring容器中的类,在其成员函数前添加@PostConstruct注解,则在执行Spring beans初始化时,就会执行该函数。
    但由于该函数执行时,其他Spring beans可能并未初始化完成,因此在该函数中执行的初始化操作应当不依赖于其他Spring beans。

    @Component
    public class Construct {
        @PostConstruct
        public void doConstruct() throws Exception {
            System.out.println("初始化:PostConstruct");
        }
    }

    CommandLineRunner

    CommandLineRunner是Spring提供的接口,定义了一个run()方法,用于执行初始化操作。

    @Component
    public class InitCommandLineRunner implements CommandLineRunner {
        @Override
        public void run(String... args) throws Exception {
            System.out.println("初始化:InitCommandLineRunner");
        }
    }

    CommandLineRunner的时机为Spring beans初始化之后,因此CommandLineRunner的执行一定是晚于@PostConstruct的。
    若有多组初始化操作,则每一组操作都要定义一个CommandLineRunner派生类并实现run()方法。这些操作的执行顺序使用@Order(n)来设置,n为int型数据。

    @Component
    @Order(99)
    public class CommandLineRunnerA implements CommandLineRunner {
        @Override
        public void run(String... args) throws Exception {
            System.out.println("初始化:CommandLineRunnerA");
        }
    }
    
    @Component
    @Order(1)
    public class CommandLineRunnerB implements CommandLineRunner {
        @Override
        public void run(String... args) throws Exception {
            System.out.println("初始化:CommandLineRunnerB");
        }
    }

    如上,会先执行CommandLineRunnerB的run(),再执行CommandLineRunnerA的run()。
    @Order(n)中的n较小的会先执行,较大的后执行。n只要是int值即可,无需顺序递增。

    ApplicationRunner

    ApplicationRunner接口与CommandLineRunner接口类似,都需要实现run()方法。二者的区别在于run()方法的参数不同:

    @Component
    public class InitApplicationRunner implements ApplicationRunner {
        @Override
        public void run(ApplicationArguments applicationArguments) throws Exception {
            System.out.println("初始化:InitApplicationRunner");
        }
    }

    ApplicationRunner接口的run()参数为ApplicationArguments对象,因此可以获取更多项目相关的内容。
    ApplicationRunner接口与CommandLineRunner接口的调用时机也是相同的,都是Spring beans初始化之后。因此ApplicationRunner接口也使用@Order(n)来设置执行顺序。

    后台兼职接单中,联系我微信:wjf88520

    by wujf

    mail:921252375@qq.com

  • 相关阅读:
    容器常用命令
    镜像常用命令
    Docker安装
    Jenkins部署
    IIS配置伪静态 集成模式 样式丢失
    centos7 apache 配置ssl
    centOS7 关闭swap
    Presto集群部署和配置
    HDFS中将普通用户增加到超级用户组supergroup
    superset在 centos 7安装运行
  • 原文地址:https://www.cnblogs.com/wujf/p/15580780.html
Copyright © 2011-2022 走看看