SpringBoot学习记录----如何启动时执行任务(CommandLineRunner和ApplicationRunner)

SpringBoot提供了CommandLineRunner和ApplicationRunner接口,让我们可以在启动项目时自动运行某些特定代码。例如一些数据的初始化,或者提前获取一些第三方接口的token。这两个接口都需要实现run方法,并以相同的方式工作。这个run方法在SpringApplication.run()完成之前调用。

1、准备工作

首先,创建一个maven项目,如何创建maven项目请参考:https://blog.youkuaiyun.com/chenzz2560/article/details/83270232。在创建完maven项目后,在pom.xml中导入SpringBoot运行需要的依赖包。

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>czz.study</groupId>
    <artifactId>springboot-runner</artifactId>
    <version>1.0-SNAPSHOT</version>

    <name>springboot-event</name>
    <description>SpringBoot Runner学习代码</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.3.RELEASE</version>
    </parent>

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

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

2、创建要运行的程序

创建一个class类,里面包含了你要启动运行的方法。@Component 注解将这个类声明为一个Bean对象,交给Spring进行管理。实现CommandLineRunner接口,实现接口中的run方法。这样,只要程序一运行,就会自动运行run中的代码。

2.1创建两个实现CommandLineRunner接口方法

package czz.study.springbootrunner.runner;

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

/**
 * 通过实现CommandLineRunner接口运行初始化代码1
 *
 * @author chenzhengzhou
 * @version 1.0
 * @date 2019/4/19 14:22
 */
@Component
@Order(value = 1)
public class CommandLineRunnerTest implements CommandLineRunner {

    @Override
    public void run(String... args) {
        System.out.println("CommandLineRunnerTest初始化代码1运行");
    }
}
package czz.study.springbootrunner.runner;

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

/**
 * 通过实现CommandLineRunner接口运行初始化代码2
 *
 * @author chenzhengzhou
 * @version 1.0
 * @date 2019/4/19 14:22
 */
@Component
@Order(value = 2)
public class CommandLineRunnerTwoTest implements CommandLineRunner {

    @Override
    public void run(String... args) {
        System.out.println("CommandLineRunnerTwoTest初始化代码2运行");
    }

}

 

2.2创建两个实现ApplicationRunner接口方法

package czz.study.springbootrunner.runner;

import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

/**
 * 通过实现ApplicationRunner接口运行初始化代码1
 *
 * @author chenzhengzhou
 * @version 1.0
 * @date 2019/4/19 14:22
 */
@Component
@Order(value = 1)
public class ApplicationRunnerTest implements ApplicationRunner {

    @Override
    public void run(ApplicationArguments args) {
        System.out.println("ApplicationRunnerTest初始化代码1运行");
    }
}
package czz.study.springbootrunner.runner;

import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
/**
 * 通过实现ApplicationRunner接口运行初始化代码2
 *
 * @author chenzhengzhou
 * @version 1.0
 * @date 2019/4/19 14:22
 */
@Component
@Order(value = 2)
public class ApplicationRunnerTwoTest implements ApplicationRunner {

    @Override
    public void run(ApplicationArguments args) {
        System.out.println("ApplicationRunnerTwoTest初始化代码2运行");
    }
}

 

3、运行程序

创建一个启动类,@SpringBootApplication 功能相当于@Configuration,@EnableAutoConfiguration,@ComponentScan这三个注解,SpringApplication.run(Main.class, args)这行代码用来声明项目入口,没有这行代码,使用的Spring注解都会失效(等于没有注解)。

package czz.study.springbootrunner;

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

@SpringBootApplication
public class SpringbootRunnerApplication {

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

4、运行结果

一个项目中可以有多个实现CommandLineRunner和ApplicationRunner接口的程序,Spring一个个执行它们,我们可以通过@Order注解来指定运行顺序,value值越小优先度越高。当优先度相同时,实现ApplicationRunner的方法会优先于实现CommandLineRunner接口的方法运行。

 

### CommandLineRunner 的作用与用法 #### 1. **CommandLineRunner 接口的定义** `CommandLineRunner` 是 Spring Boot 提供的一个接口,主要用于在应用程序启动完成后执行某些特定任务或代码块。它是一种非常灵活的机制,允许开发者在应用启动过程中插入自定义逻辑[^1]。 #### 2. **运行时机** `CommandLineRunner` 的 `run` 方法会在以下阶段被调用: - 当 `SpringApplication.run()` 被触发时,Spring Boot 开始启动应用程序。 - Spring 容器(通常是 ApplicationContext)完成初始化后,所有 Bean 已经被创建并完成了依赖注入。 - 此时,Spring Boot 会自动扫描所有实现了 `CommandLineRunner` 接口的 Bean,并按照一定顺序依次调用其 `run` 方法。 - 所有 `CommandLineRunner` 实现类的 `run` 方法执行完毕后,应用程序正式进入就绪状态[^2]。 #### 3. **基本用法** 要使用 `CommandLineRunner`,可以通过以下方式实现: ##### (1) 创建一个组件类并实现 `CommandLineRunner` 通过标注 `@Component` 将其实例化为 Spring 容器中的一个 Bean,同时重写 `run` 方法,在其中编写需要执行的业务逻辑。 ```java @Component public class MyInitService implements CommandLineRunner { @Override public void run(String... args) throws Exception { System.out.println("项目启动成功后的初始化操作..."); } } ``` ##### (2) 多个实现类的执行顺序 如果存在多个 `CommandLineRunner` 实现类,则默认情况下它们会被随机执行。为了控制执行顺序,可以引入 `@Order` 注解或者实现 `Ordered` 接口来指定优先级。数值越小,优先级越高。 ```java @Component @Order(1) public class FirstTask implements CommandLineRunner { @Override public void run(String... args) throws Exception { System.out.println("第一个任务执行"); } } @Component @Order(2) public class SecondTask implements CommandLineRunner { @Override public void run(String... args) throws Exception { System.out.println("第二个任务执行"); } } ``` #### 4. **应用场景** `CommandLineRunner` 可广泛应用于以下场景: - 数据库初始化:例如加载初始数据到数据库中[^5]。 - 缓存预热:提前填充缓存以提高性能。 - 日志记录:打印启动日志或其他调试信息。 - 自动测试:在集成测试环境中模拟用户行为。 #### 5. **与其他接口的关系** 除了 `CommandLineRunner`,Spring Boot 还提供了另一个类似的接口——`ApplicationRunner`。两者的主要区别在于参数的不同以及适用场景的选择上[^4]。 | 特性 | CommandLineRunner | ApplicationRunner | |-------------------|------------------------------------------|----------------------------------------| | 参数类型 | String 数组 | ApplicationArguments 对象 | | 使用场景 | 更适合处理命令行传参 | 支持更复杂的参数解析 | 尽管如此,对于大多数简单的启动任务来说,`CommandLineRunner` 已经足够满足需求。 --- ### 示例代码 以下是完整的示例代码展示如何使用 `CommandLineRunner` 来执行启动任务: ```java package com.example.demo; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.stereotype.Component; @SpringBootApplication public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } @Component public static class StartupTask implements CommandLineRunner { @Override public void run(String... args) throws Exception { System.out.println("Spring Boot 启动后执行任务!"); } } } ``` ---
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值