有些时候需要在项目启动后,需要加载某些资源,需要做一些初始化操作,就可以使用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");
}
}