zoukankan      html  css  js  c++  java
  • springboot-CommandLineRunner-启动时执行任务

    一、CommandLineRunner的作用

    项目启动后,执行run方法中的代码。

    如下所示:

    package org.springboot.sample.runner;
    import org.springframework.boot.CommandLineRunner;
    import org.springframework.stereotype.Component;
    
    @Component
    public class MyStartupRunner implements CommandLineRunner {
    
      @Override
      public void run(String... args) throws Exception {
        System.out.println(">>>>>>>>>>>>>>>服务启动执行,执行加载数据等操作<<<<<<<<<<<<<");
      }
    }
    

    二、如果有多个类实现CommandLineRunner接口,如何保证顺序

    使用@Order 注解,通过源码查看,order的值越小优先级越高

    如下所示:

    package org.springboot.sample.runner;
    
    import org.springframework.boot.CommandLineRunner;
    import org.springframework.core.annotation.Order;
    import org.springframework.stereotype.Component;
    
    
    @Component
    @Order(value=2)
    public class MyStartupRunner1 implements CommandLineRunner {
    
        @Override
        public void run(String... args) throws Exception {
            System.out.println(">>>>>>>>>>>>>>>服务启动执行 2222 <<<<<<<<<<<<<");
        }
    }    
    

    三、CommandLineRunner接口在SpringBoot启动时执行的顺序

    CommandLineRunner接口的run()方法会在spring bean初始化之后,SpringApplication run之前执行,可以控制在项目启动前初始化资源文件,比如初始化线程池,提前加载好加密证书等
     

    四、Springboot中的类似接口

    ApplicationRunner

     
     
  • 相关阅读:
    为什么Go没有三元运算符
    [Win10]鼠标没用,插入USB口电脑提示USB Optical Mouse找不到驱动程序的解决方案
    Office2016软件安装教程
    office2019软件安装教程
    Go语言 科学计算库 Gonum 学习1
    AI Studio 学习 Go 豆瓣电影爬取
    Git下载、安装与环境配置
    VueJS 数组哪些方法是响应式的
    VueJS v-for
    VueJS v-show
  • 原文地址:https://www.cnblogs.com/liuyp-ken/p/13203527.html
Copyright © 2011-2022 走看看