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

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");// 在这里添加初始化逻辑}
}

2.各方式执行时机对比

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

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

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

注意事项

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

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");}
}

      相关文章:

    1. MATLAB 汽车行驶过程避障模拟简化
    2. 【ACL系列论文写作指北09-参考文献与引用管理】-学术诚信与视野的体现
    3. SwiftUI 8.List介绍和使用
    4. 【广州华锐视点】AR 远程协同:突破时空限制的利器
    5. 十、名字控制(Name Control)
    6. 数据结构*栈
    7. Spring MVC 基础 - 从零构建企业级Web应用
    8. IIC 通信协议
    9. 从传统制造到智能工厂:MES如何重塑电子制造业?
    10. Airbnb更智能的搜索:嵌入式检索(Embedding-Based Retrieval,EBR)工作原理解析
    11. 使用vue3 脚手架创建项目
    12. springboot项目之websocket的坑:spring整合websocket后进行单元测试后报错的解决方案
    13. 网易大神安卓版游戏社交互动体验及功能评测
    14. C++23/26 静态反射机制深度解析:编译时元编程的新纪元
    15. 开源 Agent 框架对比:LangChain vs AutoGen vs CrewAI
    16. 这是一款好用的PDF工具!
    17. 《Q2门式起重机司机》考试大纲的专项要求有哪些?
    18. Hadoop伪分布式模式搭建全攻略:从环境配置到实战测试
    19. 使用多线程快速向Excel中快速插入一万条数据案例
    20. 使用POI和EasyExcel使用导入
    21. 买新房可申领学位,广州南沙出台购房入学政策
    22. 来伊份一季度净利减少近八成,今年集中精力帮助加盟商成功
    23. 深圳一季度GDP为8950.49亿元,同比增长5.2%
    24. 【社论】优化限购限行,激发汽车消费潜能
    25. 人社部:就业政策储备充足,将会根据形势变化及时推出
    26. 经济日报:多平台告别“仅退款”,规则调整有何影响