SpringBoot项目预加载数据——ApplicationRunner、CommandLineRunner、InitializingBean 、@PostConstruct区别

 


0、参考、业务需求

1、方式

  • 实现 ApplicationRunner 接口
  • 实现 CommandLineRunner 接口
  • 实现 InitializingBean 接口
  • 使用 @PostConstruct 标签

2、@Order

  • 可以使用@Order注解或Ordered接口改变 ApplicationRunner 和 CommandLineRunner执行顺序
  • @Order 对 InitializingBean 和 @PostConstruct 不生效。

3、测试使用

  • ApplicationRunner
@Component
@Order(3)
public class App01 implements ApplicationRunner {
@Override
public void run(ApplicationArguments args) throws Exception {
System.out.println("App01_执行了……@Order(3)");
}
}

@Component
@Order(2)
public class App02 implements ApplicationRunner {
@Override
public void run(ApplicationArguments args) throws Exception {
System.out.println("App02_执行了……@Order(2)");
}
}
  • CommandLineRunner
@Component
@Order(1)
public class Com01 implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
System.out.println("Com01_执行了……@Order(1)");
}
}

@Component
@Order(0)
public class Com02 implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
System.out.println("Com02_执行了……@Order(0)");
}
}
  • InitializingBean
/** @Order没用
* @author CC
* @since 2023/5/17 0017
*/
@Component
@Order(7)
public class Ini01 implements InitializingBean {
@Override
public void afterPropertiesSet() throws Exception {
System.out.println("Ini01_执行了……@Order(7)");
}
}

/** @Order没用
* @author CC
* @since 2023/5/17 0017
*/
@Component
@Order(4)
public class Ini02 implements InitializingBean {
@Override
public void afterPropertiesSet() throws Exception {
System.out.println("Ini02_执行了……@Order(4)");
}
}
  • @PostConstruct
/** @Order没用
* @author CC
* @since 2023/5/17 0017
*/
@Component
@Order(6)
public class Pos01 {
@PostConstruct
public void customizeName(){
System.out.println("Pos01_执行了……@Order(6)");
}
}

/** @Order没用
* @author CC
* @since 2023/5/17 0017
*/
@Component
@Order(5)
public class Pos02 {
@PostConstruct
public void customizeName(){
System.out.println("Pos02_执行了……@Order(5)");
}
}

4、执行顺序、建议使用


  • 通过实现得出执行顺序
InitializingBean > @PostConstruct > ApplicationRunner > CommandLineRunner
  • 没有执行顺序要求,使用:@PostConstruct
  • 有执行顺序要求,使用:ApplicationRunner(推荐)或者CommandLineRunner

posted on   C_C_菜园  阅读(243)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示