zoukankan      html  css  js  c++  java
  • SpringBoot应用在服务启动后进行一些初始化工作

    在一些场景中,当SpringBoot项目启动后,我们可能会需要做一些写入缓存或者初始常量信息等的初始化工作,此时便需要使用SpringBoot提供的Runner来实现。

    SpringBoot实际上给我们提供了两种在应用启动后立即执行某些方法的方式,它们分别是【ApplicationRunner】和CommandLineRunner】。两者的相同的在于它们都是在SpringApplication执行之后开始执行的,而不同点则在于CommandLineRunner接口提供的方法只能传递字符串,而ApplicationRunner是使用ApplicationArguments用来接收参数的,因此这个方式可以在更加复杂的场景中使用。

    通过实现CommandLineRunner接口来实现启动后执行特定逻辑

    @Component
    public class InitRunner implements CommandLineRunner {
        /**
         * 在服务启动完成(特指SpringApplication)后立即执行
         */
        @Override
        public void run(String... args) throws Exception {
            System.out.println("This will be executed when the project is started!");
        }
    }

     通过实现ApplicationRunner接口来实现启动后执行特定逻辑

    @Component
    public class InitRunner implements ApplicationRunner {
        /**
         * 在服务启动完成(特指SpringApplication)后立即执行
         */
        @Override
        public void run(ApplicationArguments args) throws Exception {
           System.out.println("This will be executed when the project is started!");
        }
    }

    这两种方式的实现都很简单,直接实现了相应的接口就可以了,但别忘了要在类上加上@Component注解。

    注册多个实现并指定初始化工作的优先级

    如果想要将多个初始化工作拆分开的话,只要生成多个实现类即可。

    另外如果想要指定启动方法执行的顺序的话,则可以通过实现【org.springframework.core.Ordered】接口或者使用【org.springframework.core.annotation.Order】注解来实现目的。

    @Component
    @Order(value = 1) 
    public class InitRunner1 implements ApplicationRunner {
        @Override
        public void run(ApplicationArguments args) throws Exception {       
            System.out.println("i like yanggb!");
        }    
    }
    @Component
    @Order(value = 2) 
    public class InitRunner2 implements ApplicationRunner {
        @Override
        public void run(ApplicationArguments args) throws Exception {       
            System.out.println("i like yanggb too!");
        }    
    }

    在@Order注解中指定的value值越小,则执行的优先级越高,比如在上面的代码中就会先打印出【i like yanggb!】,然后再打印出【i like yanggb too!】。

    "所有不合时宜的相遇都是遗憾。"

  • 相关阅读:
    php+GTK2 学习第二篇
    PHPMailer + qq邮箱 实现邮件发送
    HTTP状态码200、301、403、404、500等(转)
    LNMP环境搭建(转载)
    PHP+GTK2 初体验,简单计算器客户端
    mysql 用户权限管理(转)
    提高php执行效率的10条编程习惯(转)
    添加php拓展(以phppcntl及phpredis及phppcntl为例)
    centos7 &后台运行 受终端关闭影响问题
    sklearn学习笔记之简单线性回归
  • 原文地址:https://www.cnblogs.com/yanggb/p/14199482.html
Copyright © 2011-2022 走看看