SpringBoot 启动时自动执行代码的几种方式
前言
目前开发的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
注解来设定运行顺序。
代码测试
为了测试启动时运行的效果和顺序,编写几个测试代码来运行
TestPostConstruct
@Component
public class TestPostConstruct {
static {
System.out.println("static");
}
public TestPostConstruct() {
System.out.println("constructer");
}
@PostConstruct
public void init() {
System.out.println("PostConstruct");
}
}
TestApplicationRunner
@Component
@Order(1)
public class TestApplicationRunner implements ApplicationRunner{
@Override
public void run(ApplicationArguments applicationArguments) throws Exception {
System.out.println("order1:TestApplicationRunner");
}
}
TestCommandLineRunner
@Component
@Order(2)
public class TestCommandLineRunner implements CommandLineRunner {
@Override
public void run(String... strings) throws Exception {
System.out.println("order2:TestCommandLineRunner");
}
}
执行结果
总结
Spring
应用启动过程中,肯定是要自动扫描有@Component
注解的类,加载类并初始化对象进行自动注入。加载类时首先要执行static
静态代码块中的代码,之后再初始化对象时会执行构造方法。
在对象注入完成后,调用带有@PostConstruct
注解的方法。当容器启动成功后,再根据@Order
注解的顺序调用CommandLineRunner
和ApplicationRunner
接口类中的run
方法。
因此,加载顺序为static
>constructer
>@PostConstruct
>CommandLineRunner
和ApplicationRunner
.
相关文章
- 图像处理工具Python扩展库,你了解吗?
- 十个常用的损失函数解释以及Python代码实现
- 30 个数据科学工作中必备的 Python 包
- 如何在 Windows 上安装 Python
- 几行 Python 代码就可以提取数百个时间序列特征
- 使用Python快速搭建接口自动化测试脚本实战总结
- 哪种编程语言最适合开发网页抓取工具?
- 不要在 Python 中使用循环,这些方法其实更棒!
- 震惊!用Python探索《红楼梦》的人物关系!
- 如何最简单、通俗地理解Python模块?
- 酷炫,Python实现交通数据可视化!
- 为什么急于寻找Python的替代者?
- 30 个数据工程必备的Python 包
- 去字节面试被面这题能答上来吗?谈谈你对时间轮的理解?
- 火山引擎在行为分析场景下的 ClickHouse JOIN 优化
- 用Python爬取了某宝1166家月饼数据进行可视化分析,终于找到最好吃的月饼~
- 在 Linux 上试试这个基于 Python 的文件管理器
- Python列表解析式到底该怎么用?
- 如何快速把你的 Python 代码变为 API
- 十个Python初学者常犯的错误