当前位置: 首页 > 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");// 在这里添加初始化逻辑}
}

 或使用 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.mrgr.cn/news/100600.html

      相关文章:

    1. 【亚马逊云】AWS Wavelength 从理论讲解到实验演练
    2. 在 cmd shell 中执行 metasploit vbs payload
    3. 项目实战-贪吃蛇大作战【补档】
    4. 数据库安装和升级和双主配置
    5. Java读Excel:解析阿里云easyExcel导入文件的行号
    6. 人物5_My roommate
    7. yolov8+kalman 实现目标跟踪统计人流量
    8. 注意力机制:从 MHA、MQA、GQA、MLA 到 NSA、MoBA
    9. Springboot整合阿里云腾讯云发送短信验证码 可随时切换短信运营商
    10. 【LaTex】8.2 段落格式
    11. 当所有人都用上先进ai,如何保持你的优势?
    12. 统计服务器CPU、内存、磁盘、网络IO、队列、数据库占用空间等等信息
    13. Linux 定时备份到windows 方案比较
    14. [实战] IRIG-B协议详解及Verilog实现(完整代码)
    15. 麻衣相法【麻衣相士】开篇
    16. node.js 实战——mongoDB
    17. HTML标记语言_@拉钩教育【笔记】
    18. GCN+PyG 的安装与使用
    19. JAVA设计模式——(八)单例模式
    20. 深度对比:Objective-C与Swift的RunTime机制与底层原理