spring项目一启动就自动运行方法(资源加载初始化)

博客记录了Java中类初始化的几种常用方式,包括实现ApplicationRunner或CommandLineRunner的run方法、实现InitializingBean的afterPropertiesSet方法,以及利用构造方法,还提到可通过添加注解将类加载到Spring中进行初始化。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

参考一个写的不错的博客,原文请看: https://www.cnblogs.com/baixianlong/p/11117665.html

记录几种常用的方式

1、实现ApplicationRunner或CommandLineRunner的run方法

(我一般用这个比较多,比如写mq消费者达到多个消费监听的作用)

@Component
public class InitConfig implements ApplicationRunner {

    @Override
    public void run(ApplicationArguments args) throws Exception {
        // 执行初始化方法
    }
}

2、实现InitializingBean的afterPropertiesSet方法

@Component
public class InitRoute2Config implements InitializingBean {


    @Override
    public void afterPropertiesSet() throws Exception {
        // 执行方法
    }
}

3、利用构造方法

写一个类加上@Component/@Configuration/@Controller/@Service…随便一个注解,让这个类加载到spring中,我们只要写一个类构造方法,里面写初始化方法即可。因为在类注入的时候,他的构造方法也会随着这个类一起记载进去

@Component
public class A{
    public A(){
        this.init();
    }
    public void init(){
        //这里放置需要执行的代码,只要spring一启动,那么就会执行这里的代码
    }
}
<think>嗯,用户想在Spring Boot项目里让服务启动就调用某个方法。这个问题我之前可能处理过,但得仔细想想怎么正确实现。首先,Spring Boot启动时执行方法的方式有多种,我需要回忆下常见的几种方法,并比较它们的优缺点,确保推荐的方法是最合适的。 首先,用户可能不太熟悉Spring的生命周期,所以得考虑不同的方法是否适合他们的使用场景。比如,他们可能需要这个方法在应用完全启动运行,还是在某些Bean初始化之后。常见的做法有使用@PostConstruct注解、实现ApplicationRunner或CommandLineRunner接口,或者监听应用事件如ApplicationReadyEvent。 @PostConstruct注解用在Bean的方法上,会在Bean初始化完成后执行,但这时候应用可能还没完全启动,比如数据库连接还没建立,或者其他的Bean可能还没准备好。如果用户的方法依赖于这些资源,可能不适合用@PostConstruct。 然后是ApplicationRunner和CommandLineRunner,这两个接口的run方法会在SpringApplication.run()完成后执行,这时候应用上下文已经准备好了,所以可能更合适。它们的区别在于参数的不同,ApplicationRunner接收ApplicationArguments,而CommandLineRunner接收字符串数组的参数。用户如果不需要处理启动参数的话,可能两者都可以,但需要说明清楚。 另外,使用事件监听器,比如监听ApplicationReadyEvent,这样也能确保应用完全启动后才执行方法。这种方法的好处是可以更灵活地处理不同阶段的事件,但需要用户对事件监听机制有定的了解。 用户可能还不清楚这些方法之间的区别,所以需要逐解释,并给出示例代码。比如,用CommandLineRunner的话,只需要在Bean中实现接口并重写run方法。而使用@EventListener则需要在方法上添加注解,并指定监听的事件类型。 还要注意,如果有多个需要执行的方法,如何控制它们的执行顺序。比如,使用@Order注解或者在Bean定义时调整顺序。这点用户可能会遇到,所以最好提前说明。 另外,用户可能会担心这些方法是否会被执行多次,需要指出这些方法通常只会在启动时执行次,但需要确保它们所在的Bean是被Spring管理的。 最后,需要提醒用户注意方法中的异常处理,避免因为方法执行失败导致应用启动失败,或者部分资源未准备好就执行方法的问题。 总结下,可能的步骤是: 1. 介绍不同的方法及其适用场景。 2. 分别给出每种方法的代码示例。 3. 比较它们的执行时机和优缺点。 4. 提示执行顺序和异常处理。 需要确保回答结构清晰,用户能够步步理解和选择适合自己需求的方式。同时,要使用正确的中文术语,避免技术术语的混淆。</think>在Spring Boot项目中,可以通过以下几种方式实现服务启动自动调用某个方法: --- ### 方法1:使用 `CommandLineRunner` 接口 1. **实现原理** 实现`CommandLineRunner`接口的`run()`方法Spring Boot启动完成后会自动执行该方法。 2. **代码示例** ```java import org.springframework.boot.CommandLineRunner; import org.springframework.stereotype.Component; @Component public class StartupRunner implements CommandLineRunner { @Override public void run(String... args) throws Exception { yourMethod(); // 调用你的目标方法 } private void yourMethod() { System.out.println("服务启动后立即执行!"); } } ``` --- ### 方法2:使用 `ApplicationRunner` 接口 1. **与 `CommandLineRunner` 的区别** `ApplicationRunner`的`run()`方法参数为`ApplicationArguments`,可以解析带参数的启动命令。 2. **代码示例** ```java import org.springframework.boot.ApplicationArguments; import org.springframework.boot.ApplicationRunner; import org.springframework.stereotype.Component; @Component public class AppStartupRunner implements ApplicationRunner { @Override public void run(ApplicationArguments args) throws Exception { yourMethod(); } private void yourMethod() { System.out.println("通过ApplicationRunner执行"); } } ``` --- ### 方法3:使用 `@PostConstruct` 注解 1. **适用场景** 如果方法不需要等待Spring上下文完全就绪,仅需在Bean初始化后执行。 2. **代码示例** ```java import javax.annotation.PostConstruct; import org.springframework.stereotype.Component; @Component public class InitMethod { @PostConstruct public void init() { System.out.println("Bean初始化后立即执行"); } } ``` --- ### 方法4:监听 `ApplicationReadyEvent` 事件 1. **优势** 确保所有Bean初始化完成且应用完全启动后再执行。 2. **代码示例** ```java import org.springframework.boot.context.event.ApplicationReadyEvent; import org.springframework.context.event.EventListener; import org.springframework.stereotype.Component; @Component public class StartupListener { @EventListener(ApplicationReadyEvent.class) public void onApplicationReady() { yourMethod(); } private void yourMethod() { System.out.println("应用完全启动后执行"); } } ``` --- ### 方法优先级与执行顺序 1. **执行顺序** `@PostConstruct` → `CommandLineRunner/ApplicationRunner` → `ApplicationReadyEvent` (具体依赖Bean加载顺序) 2. **控制多个Runner的顺序** 使用`@Order`注解: ```java @Component @Order(1) // 数字越小优先级越高 public class FirstRunner implements CommandLineRunner { ... } ``` --- ### 注意事项 1. 如果方法涉及数据库操作,确保数据源已初始化(优先选择`ApplicationReadyEvent`)。 2. 避免在启动方法中执行阻塞操作,否则会延长服务启动时间。 3. 若需异步执行,可在方法上添加`@Async`并启用异步支持。 根据具体需求选择最适合的方式即可!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值