Spring Boot 启动后运行业务逻辑

1,235 阅读1分钟

业务场景

需要在程序启动后, 对设备SDK进行初始化

方案

总共有三种方式实现Spring Boot 启动后运行:

  • @PostConstruct
  • CommandLineRunner/ApplicationRunner
  • ContextRefreshedEvent

@PostConstruct

@PostConstruct会在所在类的构造函数执行之后执行

使用这种方式, 初始化方法所在的类必须被Spring管理

@Component
public class SDKService {
    @PostConstruct
    public void init() {
        //业务逻辑...
    }
}

CommandLineRunner/ApplicationRunner

SpringBoot在项目启动后会遍历所有实现CommandLineRunner的实体类并执行run方法

同样的, 此类必须被Spring管理

如果存在先后顺序问题, 请使用@Order注解进行排序

@Component
public class SDKInitRunner implements CommandLineRunner {

    @Override
    public void run(String... args) {
        //业务逻辑...
    }

}

ApplicationRunner和它类似, 只是run方法的参数类型为ApplicationArguments, 不再赘述

ContextRefreshedEvent

ContextRefreshedEvent, 即应用上下文刷新事件

会在Spring容器初始化完成后以及刷新时触发

此方法更适合应用于缓存?

@Component
public class SDKInitCache implements ApplicationListener<ContextRefreshedEvent> {
    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
        //业务逻辑...
    }
}

注意一点, 在web项目中, 此事件会触发两次, 笔者没有对其进行测试

总结

如果是项目启动后初始化, 建议使用CommandLineRunner/ApplicationRunner方式