Spring Boot CommandLineRunner接口详解

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

如何使用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实现。若是不显示设置web

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注解设置的顺序执行。
在这里插入图片描述spring

注意:在实现CommandLineRunner接口时,run(String… args)方法内部若是抛异常的话,会直接致使应用启动失败,因此,必定要记得将危险的代码放在try-catch代码块里。ide

本文同步分享在 博客“Μr.ηobοdy”(CSDN)。
若有侵权,请联系 support@oschina.cn 删除。
本文参与“OSC源创计划”,欢迎正在阅读的你也加入,一块儿分享。svg

相关文章
相关标签/搜索