Spring Boot CommandLineRunner接口详解

实际应用中,会有在项目服务启动的时候就去加载一些数据或做一些事情的情况。为了解决这样的问题,Spring Boot 为我们提供了一个方法,通过实现接口 CommandLineRunner 来实现,实现功能的代码放在实现的run方法中。这段初始化代码在整个应用生命周期内只会执行一次。
而且我们可以在run()方法里使用任何依赖,因为它们已经初始化好了。

如何使用CommandLineRunner接口

配合@Component注解使用

package com.nobody.config;

import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

/**
 * @Description
 * @Author Mr.nobody
 * @date 2020/8/27
 */
@Component
@Order(value = 1)
public class ApplicationStartupRunner implements CommandLineRunner {
    @Override
    public void run(String... args) throws Exception {
        System.out.println("---------- 服务启动后执行,例如执行加载数据等操作 Order=1 ----------");
    }
}

配合@SpringBootApplication注解使用

package com.nobody;

import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Application implements CommandLineRunner {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

    @Override
    public void run(String... args) throws Exception {
        System.out.println("---------- 服务启动后执行,例如执行加载数据等操作 ----------");
    }
}

多个CommandLineRunner实现类的执行顺序问题

一个应用可能存在多个CommandLineRunner接口实现类,如果我们想设置它们的执行顺序,可以使用 @Order实现。如果不显示设置

package com.nobody.config;

import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

/**
 * @Description
 * @Author Mr.nobody
 * @date 2020/8/27
 */
@Component
@Order(value = 2)
public class ApplicationOrderStartupRunner implements CommandLineRunner {
    @Override
    public void run(String... args) throws Exception {
        System.out.println("---------- 服务启动后执行,例如执行加载数据等操作 Order=2 ----------");
    }
}

启动服务,可以在控制台看到在Spring Boot启动完之后,执行了多个定义的CommandLineRunner实现类的run方法,并且按@Order注解设置的顺序执行。
在这里插入图片描述

注意:在实现CommandLineRunner接口时,run(String… args)方法内部如果抛异常的话,会直接导致应用启动失败,所以,一定要记得将危险的代码放在try-catch代码块里。

猜你喜欢

转载自blog.csdn.net/chenlixiao007/article/details/108258437