0、参考、业务需求
1、方式
- 实现 ApplicationRunner 接口
- 实现 CommandLineRunner 接口
- 实现 InitializingBean 接口
- 使用 @PostConstruct 标签
2、@Order
- 可以使用@Order注解或Ordered接口改变 ApplicationRunner 和 CommandLineRunner执行顺序
- @Order 对 InitializingBean 和 @PostConstruct 不生效。
3、测试使用
| @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)"); |
| } |
| |
| } |
| @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)"); |
| } |
| |
| } |
| |
| |
| |
| |
| @Component |
| @Order(7) |
| public class Ini01 implements InitializingBean { |
| |
| @Override |
| public void afterPropertiesSet() throws Exception { |
| System.out.println("Ini01_执行了……@Order(7)"); |
| } |
| |
| } |
| |
| |
| |
| |
| @Component |
| @Order(4) |
| public class Ini02 implements InitializingBean { |
| |
| @Override |
| public void afterPropertiesSet() throws Exception { |
| System.out.println("Ini02_执行了……@Order(4)"); |
| } |
| |
| } |
| |
| |
| |
| |
| @Component |
| @Order(6) |
| public class Pos01 { |
| |
| @PostConstruct |
| public void customizeName(){ |
| System.out.println("Pos01_执行了……@Order(6)"); |
| } |
| |
| } |
| |
| |
| |
| |
| @Component |
| @Order(5) |
| public class Pos02 { |
| |
| @PostConstruct |
| public void customizeName(){ |
| System.out.println("Pos02_执行了……@Order(5)"); |
| } |
| |
| } |
4、执行顺序、建议使用

| InitializingBean > @PostConstruct > ApplicationRunner > CommandLineRunner |
- 没有执行顺序要求,使用:@PostConstruct
- 有执行顺序要求,使用:ApplicationRunner(推荐)或者CommandLineRunner
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)