项目启动自动执行代码方式
SpringBoot项目在启动的时候需要预加载一些资源。
如何实现启动过程中执行代码,或启动成功后自动执行代码?
- 在static代码块中实现
- 在构造方法里实现
- 使用
@PostConstruct
注解实现- 也可以实现Spring的
ApplicationRunner
与CommandLineRunner
接口去实现启动后运行的功能。
java自身的启动时加载方式
static
代码块:static
静态代码块,在类加载的时候即自动执行。构造方法:在对象初始化时执行。执行顺序在
static
静态代码块之后。
Spring启动时加载方式
@PostConstruct
注解:@PostConstruct
注解使用在方法上,这个方法在对象依赖注入初始化之后执行。
ApplicationRunner
和CommandLineRunner
:SpringBoot提供了两个接口来实现Spring容器启动完成后执行的功能,两个接口分别为CommandLineRunner
和ApplicationRunner
。这两个接口需要实现一个run
方法,将代码在run
中实现即可。这两个接口功能基本一致,其区别在于
run
方法的入参。ApplicationRunner
的run
方法入参为ApplicationArguments
,而CommandLineRunner
的run
方法入参为String[]
数组。
何为ApplicationArguments
:
在Spring应用运行时使用的访问应用参数。即我们可以获取到SpringApplication.run(…)
的应用参数。
Order注解:
当有多个类实现了CommandLineRunner
和ApplicationRunner
接口时,可以通过在类上添加@Order
注解来设定运行顺序。
/**
* 测试加载顺序
*/
@Component
public class TestPostConstruct {
static {
System.out.println("static代码块。。。");
}
public TestPostConstruct() {
System.out.println("constructer构造函数。。。");
}
@PostConstruct
public void init() {
System.out.println("@PostConstruct注解。。。");
}
}
TestApplicationRunner实现ApplicationRunner接口
@Component
@Order(1) // 加载顺序 1
public class TestApplicationRunner implements ApplicationRunner{
@Override
public void run(ApplicationArguments applicationArguments) throws Exception {
System.out.println("order1:实现ApplicationRunner接口。。。");
}
}
TestCommandLineRunner实现CommandLineRunner接口
@Component
@Order(2) // 加载顺序 2
public class TestCommandLineRunner implements CommandLineRunner {
@Override
public void run(String... strings) throws Exception {
System.out.println("order2:实现CommandLineRunner接口。。。");
}
}
执行结果:
static
:静态代码块最先执行
constructer
:构造方法是在static
后执行
@PostConstruct
:该注解是在静态代码块和构造方法之后执行实现
ApplicationRunner
和CommandLineRunner
接口的类的执行顺序由@Order
注解控制。
小结:
Spring应用启动过程中,首先要自动扫描有
@Component
注解的类,加载类并初始化对象进行自动注入。
static
:加载类时首先要执行static
静态代码块中的代码constructer
:之后再初始化对象时会执行构造方法@PostConstruct
:在对象注入完成后,调用带有@PostConstruct
注解的方法。- 接口:当容器启动成功后,再根据
@Order
注解的顺序调用CommandLineRunner
和ApplicationRunner
接口类中的run
方法。
加载顺序:static
>constructer
>@PostConstruct
>CommandLineRunner
和ApplicationRunner