【Spring Boot 启动时自动执行代码的几种方式,还有谁不会??】来源:blog.csdn.net/u011291072/article/details/81813662
前言目前开发的SpringBoot项目在启动的时候需要预加载一些资源 。而如何实现启动过程中执行代码,或启动成功后执行,是有很多种方式可以选择,我们可以在static代码块中实现,也可以在构造方法里实现,也可以使用@PostConstruct注解实现 。
当然也可以去实现Spring的ApplicationRunner与CommandLineRunner接口去实现启动后运行的功能 。在这里整理一下,在这些位置执行的区别以及加载顺序 。
java自身的启动时加载方式static代码块static静态代码块,在类加载的时候即自动执行 。
构造方法在对象初始化时执行 。执行顺序在static静态代码块之后 。
Spring启动时加载方式@PostConstruct注解PostConstruct注解使用在方法上,这个方法在对象依赖注入初始化之后执行 。
ApplicationRunner和CommandLineRunnerSpringBoot提供了两个接口来实现Spring容器启动完成后执行的功能,两个接口分别为CommandLineRunner和ApplicationRunner 。
这两个接口需要实现一个run方法,将代码在run中实现即可 。这两个接口功能基本一致,其区别在于run方法的入参 。ApplicationRunner的run方法入参为ApplicationArguments,为CommandLineRunner的run方法入参为String数组 。
何为ApplicationArguments官方文档解释为:
Provides access to the arguments that were used to run a SpringApplication.
在Spring应用运行时使用的访问应用参数 。即我们可以获取到SpringApplication.run(…)的应用参数 。
Order注解当有多个类实现了CommandLineRunner和ApplicationRunner接口时,可以通过在类上添加@Order注解来设定运行顺序 。
代码测试为了测试启动时运行的效果和顺序,编写几个测试代码来运行看看 。
Spring Boot 基础就不介绍了,推荐下这个实战教程:https://github.com/javastacks/spring-boot-best-practice
TestPostConstruct
@Componentpublic class TestPostConstruct {static {System.out.println("static");}public TestPostConstruct() {System.out.println("constructer");}@PostConstructpublic void init() {System.out.println("PostConstruct");}}TestApplicationRunner
@Component@Order(1)public class TestApplicationRunner implements ApplicationRunner{@Overridepublic void run(ApplicationArguments applicationArguments) throws Exception {System.out.println("order1:TestApplicationRunner");}}TestCommandLineRunner
@Component@Order(2)public class TestCommandLineRunner implements CommandLineRunner {@Overridepublic void run(String... strings) throws Exception {System.out.println("order2:TestCommandLineRunner");}}执行结果

文章插图
总结Spring应用启动过程中,肯定是要自动扫描有
@Component注解的类,加载类并初始化对象进行自动注入 。加载类时首先要执行static静态代码块中的代码,之后再初始化对象时会执行构造方法 。在对象注入完成后,调用带有
@PostConstruct注解的方法 。当容器启动成功后,再根据@Order注解的顺序调用CommandLineRunner和ApplicationRunner接口类中的run方法 。因此,加载顺序为
static>constructer>@PostConstruct>CommandLineRunner和ApplicationRunner.近期热文推荐:
1.1,000+ 道 Java面试题及答案整理(2022最新版)
2.劲爆!Java 协程要来了 。。。
3.Spring Boot 2.x 教程,太全了!
4.别再写满屏的爆爆爆炸类了,试试装饰器模式,这才是优雅的方式!!
5.《Java开发手册(嵩山版)》最新发布,速速下载!
觉得不错,别忘了随手点赞+转发哦!
- 春季老年人吃什么养肝?土豆、米饭换着吃
- 三八妇女节节日祝福分享 三八妇女节节日语录
- 老人谨慎!选好你的“第三只脚”
- 校方进行了深刻的反思 青岛一大学生坠亡校方整改校规
- 脸皮厚的人长寿!有这特征的老人最长寿
- 长寿秘诀:记住这10大妙招 100%增寿
- 春季老年人心血管病高发 3条保命要诀
- 眼睛花不花要看四十八 老年人怎样延缓老花眼
- 香槟然能防治老年痴呆症? 一天三杯它人到90不痴呆
- 老人手抖的原因 为什么老人手会抖
