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

posted @   harrychinese  阅读(3295)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
点击右上角即可分享
微信分享提示