当前位置: 首页 > ai >正文

SpringBoot启动后自动执行方法的各种方式-笔记

1. SpringBoot启动后自动执行方法的各种方式

1.1 @PostConstruct 注解

作用:在依赖注入完成后执行初始化方法。

适用场景:需要在Bean初始化时执行某些操作(如配置、预加载数据)。

注意:该方法在Bean初始化阶段执行,此时应用可能未完全启动(如数据库连接未就绪)。

示例代码:

import javax.annotation.PostConstruct;
import org.springframework.stereotype.Component;@Component
public class MyPostConstructBean {@PostConstructpublic void init() {System.out.println("PostConstruct 方法执行");// 执行初始化逻辑}
}

1.2. 实现 InitializingBean 接口

作用:通过重写 afterPropertiesSet 方法实现初始化。

适用场景:需要在属性注入后执行操作,与 @PostConstruct 类似但需实现接口。

示例代码:

import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;@Component
public class MyInitializingBean implements InitializingBean {@Overridepublic void afterPropertiesSet() throws Exception {System.out.println("InitializingBean 的 afterPropertiesSet 方法执行");// 执行初始化逻辑}
}

1.3. 实现 ApplicationRunner 接口

作用:在Spring应用上下文刷新后执行,支持接收命令行参数。

适用场景:需要在应用启动完成后执行操作,此时Bean已初始化完毕。

示例代码:

import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;@Component
public class MyApplicationRunner implements ApplicationRunner {@Overridepublic void run(ApplicationArguments args) throws Exception {System.out.println("ApplicationRunner 执行");// 执行逻辑,可访问命令行参数 args}
}

1.4. 实现 CommandLineRunner 接口

作用:与 ApplicationRunner 类似,但参数为 String[]

适用场景:需要接收简单命令行参数时使用。

示例代码:

import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;@Component
public class MyCommandLineRunner implements CommandLineRunner {@Overridepublic void run(String... args) throws Exception {System.out.println("CommandLineRunner 执行");// 执行逻辑,可访问 args 参数}
}

1.5. 实现 ApplicationListener 接口

作用:通过 ApplicationListener 监听应用完全启动事件。

适用场景:需要在应用完全就绪后执行操作(如启动后发送通知)。

示例代码:

import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;@Component
public class MyApplicationListener implements ApplicationListener<ApplicationReadyEvent> {@Overridepublic void onApplicationEvent(ApplicationReadyEvent event) {System.out.println("ApplicationReadyEvent 触发,应用已启动");// 执行逻辑,此时可安全访问所有Bean}
}

1.6. 使用 @Bean 的 initMethod 属性

作用:在Spring配置类中定义Bean时,通过 initMethod 指定初始化方法。

示例代码:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;@Configuration
public class AppConfig {@Bean(initMethod = "init")public MyBean myBean() {return new MyBean();}
}public class MyBean {public void init() {System.out.println("应用启动后执行: initMethod");// 在这里添加初始化逻辑}
}

 或使用 init-method 属性(XML 配置):

<bean id="myBean" class="com.example.MyBean" init-method="init"/>

2.各方式执行时机对比

方法执行时机
@PostConstructBean 初始化完成后(属性注入后)。
InitializingBean与 @PostConstruct 类似,属性注入后。
ApplicationRunner应用上下文刷新后,ApplicationReadyEvent 触发前。
CommandLineRunner同上。
ApplicationListener应用完全就绪(所有Bean初始化完成,所有启动任务执行完毕)。

根据需求选择合适的方式:

  • 需要访问数据库或资源时,建议使用 ApplicationListener 或 CommandLineRunner
  • 简单的Bean初始化逻辑可用 @PostConstruct 或 InitializingBean

注意事项

  1. 线程问题:默认在主线程执行,避免长时间阻塞操作,可考虑异步执行(如结合 @Async)。
  2. 依赖注入:在 @PostConstruct 和 InitializingBean 中无法直接访问其他Bean(需等待初始化完成)。
  3. 顺序控制:通过 @Order 或实现 Ordered 接口控制多个启动任务的顺序。

相关文档:InitializingBean接口和@PostConstruct-笔记-CSDN博客

3.使用 @Order 控制执行顺序

作用:通过 @Order 或实现 Ordered 接口控制多个启动任务的执行顺序。

示例:在 ApplicationRunner 中使用 @Order

import org.springframework.boot.ApplicationRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;@Component
@Order(1)  // 数值越小优先级越高
public class FirstRunner implements ApplicationRunner {@Overridepublic void run(ApplicationArguments args) {System.out.println("第一个执行的 Runner");}
}@Component
@Order(2)
public class SecondRunner implements ApplicationRunner {@Overridepublic void run(ApplicationArguments args) {System.out.println("第二个执行的 Runner");}
}
      http://www.xdnf.cn/news/2710.html

      相关文章:

    1. 【MCP】第三篇:Cline工具链路追踪——解码“协议引擎“的神经传导奥秘
    2. Pytest-mark使用详解(跳过、标记、参数 化)
    3. 夜莺 v8.0.0-beta.10 部署
    4. 新能源汽车声纹监测技术的发展趋势是什么?
    5. 机器学习:【抛掷硬币的贝叶斯后验概率】
    6. 【MySQL】-- 增删改查操作(1)
    7. AI辅助编程-cursor开发煤矿持证上岗管理程序需求与设计篇
    8. python tk.text不可编辑
    9. 高效运维,智慧监测:COMEM光纤温度测量系统在电力行业中的应用
    10. 云服务器被黑客攻击应急响应与加固指南(上)
    11. Shiro学习(七):总结Shiro 与Redis 整合过程中的2个问题及解决方案
    12. 网络安全入门综述
    13. 深入了解指针(6)
    14. day004-习题
    15. Python实例题:Pvthon实现键值数据库
    16. 入门版 鸿蒙 组件导航 (Navigation)
    17. 游戏打击感实现
    18. frp内网穿透的基础使用
    19. 如何选择靠谱的软件测试外包公司?软件测试外包需要多少费用和时间?
    20. Python抽象类:ABC模块的优雅之道与手动实现的隐性陷阱
    21. QT采用mqtt进行通信(17.1)
    22. 【JavaScript】if语句
    23. 云服务器主动防御策略与自动化防护(下)
    24. QgraphicsView异步线程加载地图瓦片
    25. 【LInux网络】数据链路层 - 深度理解以太网和APR协议
    26. gdb 源码安装
    27. 软考-软件设计师中级备考 5、数据结构 树和二叉树
    28. Improving Deep Learning For Airbnb Search
    29. linux常用操作命令
    30. 小草GrassRouter多卡聚合路由器聚合卫星、MESH网络应用解决方案