zoukankan      html  css  js  c++  java
  • SpringBoot系列: CommandLineRunner接口的用处

    ========================================
    使用 CommandLineRunner 对Spring Bean进行额外初始化
    ========================================

    如果想要在Spring 容器初始化做一些额外的工作, 比如要对Spring Bean 对象做一些额外的工作, 首先想到的方式是, 直接将代码写在 main() 函数的 SpringApplication.run()后, 比如:

    @SpringBootApplication
    public class PebbleDemoApplication {
    
        public static void main(String[] args) throws IOException {
            SpringApplication.run(PebbleDemoApplication.class, args);
            
            //done something here 
        }
    }

    其实, 这样的方式的方式不行的, 在main()方法中, 要想访问到Spring 中的 bean 对象, 并不容易.有两个方法:

    方法1: 入口类中, 新增一个函数, 打上注解 @PostConstruct , 则这个函数在入口类初始化完成后被调用. 

    方法2: Spring Boot 为我们提供了更好的方式, 即声明我们自己的 CommandLineRunner Bean.

    具体为: 新建类去实现 CommandLineRunner 接口, 同时为类加上 @Component 注解.
    当Spring 容器初始化完成后, Spring 会遍历所有实现 CommandLineRunner 接口的类, 并运行其run() 方法.
    这个方式是最推荐的, 原因是:
    1. 因为 Runner 类也是 @Component 类, 这样就能利用上Spring的依赖注入, 获取到 Spring 管理的bean对象.
    2. 可以创建多个 Runner 类, 为了控制执行顺序, 可以加上 @Order 注解, 序号越小越早执行.

    下面代码打印文本的顺序是:  step 1 -> step 3 -> step 4 -> step 5

    @SpringBootApplication
    public class PebbleDemoApplication {
    
        public static void main(String[] args) throws IOException {
            System.out.println("Step 1:  The service will  start");    //step 1
            SpringApplication.run(PebbleDemoApplication.class, args);  //step 2
            System.out.println("Step 5: The service has started");     //step 5
        }
    }
    
    
    @Component
    @Order(1)
    class Runner1 implements CommandLineRunner {
        @Override
        public void run(String... args) throws Exception {
            System.out.println("Step 3: The Runner1 run ...");
        }
    }
    
    @Component
    @Order(2)
    class Runner2 implements CommandLineRunner {
        @Override
        public void run(String... args) throws Exception {
            System.out.println("Step 4: The Runner2 run ...");
        }
    }

    ========================================
    使用 CommandLineRunner 创建纯粹的命令行程序
    ========================================
    步骤:
    1. pom.xml 中要将 spring-boot-starter-web 依赖去除, 换上 spring-boot-starter 基础依赖包.
    2. 按照上面的方式3, 新建 CommandLineRunner 类, 并声明为 @Component.

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter</artifactId>
    </dependency> 

    =======================================
    参考
    =======================================
    http://www.ityouknow.com/springboot/2018/05/03/spring-boot-commandLineRunner.html

  • 相关阅读:
    Java各种数据结构实现
    Lintcode答案&笔记
    JavaScript之onclick事件
    CSS3过渡结束监听事件,清除/修改表单元素的一些默认样式
    移动端自动调整根元素字体大小
    手机移动端事件封装
    js 拖拽 鼠标事件,放大镜效果
    CSS 常用属性之 阴影
    CSS常用属性之选择器
    全屏banner及全屏轮播
  • 原文地址:https://www.cnblogs.com/harrychinese/p/SpringBoot_CommandLineRunner.html
Copyright © 2011-2022 走看看