Spring Boot 启动进行初始化操作

174 阅读1分钟

有些时候需要在项目启动后,需要加载某些资源,需要做一些初始化操作,就可以使用Spring boot中的几种方式来实现

一、@PostConstruct注解

对于注入到Spring容器中的类,在其成员函数前添加@PostConstruct注解,则在执行Spring beans初始化时,就会执行该函数。

但由于该函数执行时,其他Spring beans可能并未初始化完成,因此在该函数中执行的初始化操作应当不依赖于其他Spring beans。

@Component
public class Construct {
    @PostConstruct
    public void doConstruct() throws Exception {
        System.out.println("初始化:PostConstruct");
    }
}
​

二、CommandLineRunner接口

CommandLineRunner是Spring提供的接口,定义了一个run()方法,用于执行初始化操作。

@Component
public class InitCommandLineRunner implements CommandLineRunner {
    @Override
    public void run(String... args) throws Exception {
        System.out.println("初始化:InitCommandLineRunner");
    }
}

CommandLineRunner的时机为Spring beans初始化之后,因此CommandLineRunner的执行一定是晚于@PostConstruct的。

三、ApplicationRunner接口

ApplicationRunner接口与CommandLineRunner接口类似,都需要实现run()方法。二者的区别在于run()方法的参数不同。

@Component
public class InitApplicationRunner implements ApplicationRunner {
    @Override
    public void run(ApplicationArguments applicationArguments) throws Exception {
        System.out.println("初始化:InitApplicationRunner");
    }
}

原文链接:blog.csdn.net/fyyyr/artic…