在SpringBoot项目启动时需要预先去加载执行一些方法
Java自身的启动方式
static代码块
static静态代码块,在类加载的时候即自动执行。
构造方法
在对象初始化时执行。执行顺序在static静态代码块之后。
Spring启动时加载方式
@PostConstruct注解
@PostConstruct
注解使用在方法上,这个方法在对象依赖注入初始化之后执行
ApplicationRunner和CommandLineRunner
SpringBoot提供了两个接口来实现Spring容器启动完成后执行的功能,两个接口分别为CommandLineRunner和 ApplicationRunner
。
这两个接口需要实现一个run方法,将代码在run中实现即可。这两个接口功能基本一致,其区别在于run方法的入参。ApplicationRunner
的run方法入参为 ApplicationArguments
,为 CommandLineRunner
的run方法入参为String数组。
加载顺序为 static>constructer>@PostConstruct>CommandLineRunner
和 ApplicationRunner.
评论区