本文最后更新于 200 天前 ,文中信息可能已经过时。如有问题请在评论区留言。

为了实现在 Spring Boot 工程启动后,自动执行特定方法的功能,我们可以通过以下方式实现。

CommandLineRunner

实现 CommandLineRunner 接口,在 run 方法里面调用需要执行的方法即可。

特定:

  • 方式执行时,项目已初始化完毕,可提供正常服务。
  • 可以接受参数,不限制格式。项目启动时传入参数:java -jar example.jar arg1 arg2 arg3
  • 可直接注入 Spring IoC 容器的 bean。

代码示例:

java
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

@Component
public class Runner implements CommandLineRunner {
    @Override
    public void run(String... args) throws Exception {
        // todo your code
    }
}

ApplicationRunner

实现 ApplicationRunner 接口与实现 CommandLineRunner 接口基本一致。

唯一不同是启动是参数的格式:CommandLineRunner 对于参数格式没有限制,ApplicationRunner 接口参数格式必须是 -key=value

代码示例:

java
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

@Component
public class Runner implements ApplicationRunner {

    @Override
    public void run(ApplicationArguments args) throws Exception {
        // todo your code
    }
}

ApplicationListener

实现接口 ApplicationListener 方式和实现 ApplicationRunnerCommandLineRunner 接口都不影响服务,均可正常提供服务。

为了可以直接注入 bean,监听事件一般为 ApplicationStartedEventApplicationReadyEvent,其他事件可能无法正常注入 bean。

代码示例:

java
ApplicationStartedEvent
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
import org.springframework.boot.context.event.ApplicationStartedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

@Component
public class Runner implements ApplicationListener<ApplicationStartedEvent> {
    @Override
    public void onApplicationEvent(ApplicationStartedEvent event) {
        // todo your code
    }
}
java
ApplicationReadyEvent
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

@Component
public class Runner implements ApplicationListener<ApplicationReadyEvent> {
    @Override
    public void onApplicationEvent(ApplicationReadyEvent event) {
        // todo your code
    }
}

其他方式

你也可以通过自定义 Spring Bean 初始化逻辑来实现程序启动时自动执行方法。 但一般此类方式均在项目启动过程中执行,且执行过程期间无法提供正常服务。 如使用 @PostConstruct 注解、实现 InitializingBean 接口、指定 init-method 方法等。

执行顺序

  1. 其他方式(通过自定义 Bean 初始化逻辑)始终最先执行。
  2. 如果监听 ApplicationStartedEvent 事件,则一定会在 CommandLineRunnerApplicationRunner 之前执行。
  3. 如果监听 ApplicationReadyEvent 事件,则一定会在 CommandLineRunnerApplicationRunner 之后执行。
  4. CommandLineRunnerApplicationRunner 默认是 ApplicationRunner 先执行。如果指定了 @Order 则按照 @Order 大的先执行。