概述
目前开发的SpringBoot项目在启动的时候需要做一些数据缓存、加载一些资源。最常见的可以去实现Spring的ApplicationRunner
与CommandLineRunner
接口去实现启动后运行的功能。查阅资料可以知道可以自动运行代码的方式很多包括:
java自身的启动时加载方式
static静态代码块,在类加载的时候即自动执行。
在对象初始化时执行。执行顺序在static静态代码块之后。
Spring启动时加载方式
PostConstruct注解使用在方法上,这个方法在对象依赖注入初始化之后执行。
ApplicationRunner和CommandLineRunner
SpringBoot提供了两个接口来实现Spring容器启动完成后执行的功能,两个接口分别为CommandLineRunner
和ApplicationRunner
。
这两个接口需要实现一个run方法,将代码在run中实现即可。这两个接口功能基本一致,其区别在于run方法的入参。ApplicationRunner
的run方法入参为ApplicationArguments
,为CommandLineRunner
的run方法入参为String数组。
举个例子,在Springboot项目中添加以下类,添加到自动扫描包下面
@Component
public class TestPostConstruct {
static {
System.out.println("static");
}
public TestPostConstruct() {
System.out.println("constructer");
}
@PostConstruct
public void init2() {
System.out.println("PostConstruct2");
}
@PostConstruct
public void init1() {
System.out.println("PostConstruct1");
}
@PostConstruct
public void init() {
System.out.println("PostConstruct");
}
}
@Component
public class TestApplicationRunner implements ApplicationRunner {
@Override
public void run(ApplicationArguments applicationArguments) throws Exception {
System.out.println("TestApplicationRunner");
}
}
@Component
public class TestCommandLineRunner implements CommandLineRunner {
@Override
public void run(String... strings) throws Exception {
System.out.println("TestCommandLineRunner");
}
}
项目启动结果
Spring应用启动过程中,肯定是要自动扫描有@Component
注解的类,加载类并初始化对象进行自动注入。加载类时首先要执行static静态代码块中的代码,之后再初始化对象时会执行构造方法。
在对象注入完成后,调用带有@PostConstruct
注解的方法。当容器启动成功后,再根据@Order注解的顺序调用CommandLineRunner
和ApplicationRunner
接口类中的run方法。
当有多个@PostConstruct
注解的方法时先运行init方法,其余方法顺序运行。
结论
加载顺序为static
>constructer
>@PostConstruct
>CommandLineRunner
和ApplicationRunner
.