侧边栏壁纸
博主头像
抱头虎窜

行动起来,活在当下

  • 累计撰写 10 篇文章
  • 累计创建 18 个标签
  • 累计收到 0 条评论

目 录CONTENT

文章目录

SpringBoot启动时预执行

LuLu
2025-06-17 / 0 评论 / 0 点赞 / 0 阅读 / 0 字

在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>CommandLineRunnerApplicationRunner.

0

评论区