Spring Boot 如何解决项目启动时初始化资源

这个神器就是 CommandLineRunner,ApplicationRunner 

 CommandLineRunner 接口的 Component 会在所有 SpringBeans都初始化之后, SpringApplication.run()之前执行,非常适合在应用程序启动之初进行一些数据初始化的工作。

如果我们在启动容器的时候需要初始化很多资源,并且初始化资源相互之间有序,那如何保证不同的 CommandLineRunner 的执行顺序呢?Spring Boot 也给出了解决方案。那就是使用 @Order 注解。

用法:

@Component
@Order(1)
public class OrderRunner1 implements CommandLineRunner {
    @Override
    public void run(String... args) throws Exception {
        System.out.println("The OrderRunner1 start to initialize ...");
    }
}

注意:一定要有@Component这个注解。要不然SpringBoot扫描不到这个类,是不会执行。

添加 @Order 注解的实现类最先执行,并且 @Order()里面的值越小启动越早。

在实践中,使用 ApplicationRunner 用法相同

猜你喜欢

转载自my.oschina.net/goodyj/blog/1824336