SpringBoot启动后运行代码的几种方法

 更新时间:2025年06月18日 09:23:49   作者:1010n111  
在开发SpringBoot应用时,有时需要在应用启动后执行一些特定的代码,例如监控目录变化、初始化数据等,然而,直接在启动时运行代码可能会遇到@Autowired服务未初始化的问题,因此需要找到合适的时机来执行这些代码,所以本文给大家介绍了SpringBoot启动后运行代码的几种方法

Spring Boot启动后运行代码的方法

实现步骤

1. 使用ApplicationReadyEvent

ApplicationReadyEvent会在应用刷新并处理完所有相关回调后触发,表明应用已准备好处理请求。可以通过@EventListener注解监听该事件。

import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

@Component
public class StartupRunner {

    @EventListener(ApplicationReadyEvent.class)
    public void doSomethingAfterStartup() {
        System.out.println("hello world, I have just started up");
    }
}

2. 实现ApplicationListener<ApplicationReadyEvent>接口

创建一个类实现ApplicationListener<ApplicationReadyEvent>接口,并重写onApplicationEvent方法。

import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

@Component
public class ApplicationStartup implements ApplicationListener<ApplicationReadyEvent> {

    @Override
    public void onApplicationEvent(final ApplicationReadyEvent event) {
        // 这里编写你的代码
    }
}

3. 使用CommandLineRunner或ApplicationRunner

CommandLineRunnerApplicationRunner是Spring Boot提供的接口,实现这些接口并重写run方法,Spring Boot会在应用启动过程的末尾执行这些方法。

import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

@Component
public class CommandLineAppStartupRunner implements CommandLineRunner {

    @Override
    public void run(String... args) throws Exception {
        System.out.println("Application started with command-line arguments: " + String.join(", ", args));
    }
}

4. 使用@PostConstruct注解

在一个@Component类中使用@PostConstruct注解的方法会在Bean初始化完成后执行。

import javax.annotation.PostConstruct;
import org.springframework.stereotype.Component;

@Component
public class Monitor {

    @PostConstruct
    public void init() {
        // 在这里启动监控
    }
}

5. 使用SmartInitializingSingleton

在Spring 4.1及以上版本中,可以使用SmartInitializingSingleton,它会在所有单例Bean初始化完成后回调。

import org.springframework.beans.factory.SmartInitializingSingleton;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class AppConfig {

    @Bean
    public SmartInitializingSingleton importProcessor() {
        return () -> {
            // 执行任务
        };
    }
}

核心代码

以下是几种方法的核心代码示例:

使用ApplicationReadyEvent

import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

@Component
public class StartupExample {

    @EventListener(ApplicationReadyEvent.class)
    public void executeAfterStartup() {
        System.out.println("执行启动后任务");
    }
}

使用CommandLineRunner

import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

@Component
public class CommandLineExample implements CommandLineRunner {

    @Override
    public void run(String... args) throws Exception {
        System.out.println("使用CommandLineRunner执行任务");
    }
}

使用@PostConstruct

import javax.annotation.PostConstruct;
import org.springframework.stereotype.Component;

@Component
public class PostConstructExample {

    @PostConstruct
    public void init() {
        System.out.println("使用@PostConstruct执行任务");
    }
}

最佳实践

  • 如果代码需要在应用准备好处理请求后执行,推荐使用ApplicationReadyEvent。
  • 如果需要处理命令行参数,可以使用CommandLineRunner或ApplicationRunner。
  • 如果代码是与Bean初始化相关的,可以使用@PostConstruct注解。
  • 如果需要在所有单例Bean初始化完成后执行代码,可以使用SmartInitializingSingleton。

常见问题

  • @Autowired服务未初始化:使用ApplicationReadyEvent、CommandLineRunner、ApplicationRunner或SmartInitializingSingleton可以确保@Autowired服务已初始化。
  • @PostConstruct方法执行过早:@PostConstruct方法在Bean初始化时执行,可能会在应用整体准备好之前执行。如果需要在应用准备好后执行,不建议使用该注解。
  • ContextRefreshedEvent多次触发:ContextRefreshedEvent可能会多次触发,需要在代码中添加判断逻辑,避免重复执行。

以上就是SpringBoot启动后运行代码的几种方法的详细内容,更多关于SpringBoot启动后运行代码的资料请关注脚本之家其它相关文章!

相关文章

  • 详解Spring循环依赖的解决方案

    详解Spring循环依赖的解决方案

    这篇文章主要介绍了详解Spring循环依赖的解决方案,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2018-05-05
  • Java实现浏览器端大文件分片上传

    Java实现浏览器端大文件分片上传

    本文主要介绍了Java实现浏览器端大文件分片上传,文中通过示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2021-08-08
  • Maven使用集成测试的示例代码

    Maven使用集成测试的示例代码

    本文介绍了在Maven项目中使用maven-failsafe-plugin插件进行集成测试,步骤包括添加测试依赖、编写集成测试类、配置插件、运行测试以及查看和分析测试结果,感兴趣的可以了解一下
    2024-11-11
  • IntelliJ IDEA查看方法说明文档的图解

    IntelliJ IDEA查看方法说明文档的图解

    今天小编就为大家分享一篇关于IntelliJ IDEA查看方法说明文档的图解,小编觉得内容挺不错的,现在分享给大家,具有很好的参考价值,需要的朋友一起跟随小编来看看吧
    2018-10-10
  • Java和Scala集合间的相互转换方式

    Java和Scala集合间的相互转换方式

    这篇文章主要介绍了Java和Scala集合间的相互转换方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2021-10-10
  • Java如何定义Long类型

    Java如何定义Long类型

    这篇文章主要介绍了Java如何定义Long类型,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2022-07-07
  • mybatis中insert主键ID获取和多参数传递的示例代码

    mybatis中insert主键ID获取和多参数传递的示例代码

    这篇文章主要介绍了mybatis中insert主键ID获取和多参数传递的示例代码,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2021-03-03
  • jar包中替换指定的class文件方法详解

    jar包中替换指定的class文件方法详解

    这篇文章主要为大家介绍了jar包中替换指定的class文件方法详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2023-11-11
  • 解决IDEA 左侧Project中没有out文件夹的问题

    解决IDEA 左侧Project中没有out文件夹的问题

    这篇文章主要介绍了解决IDEA 左侧Project中没有out文件夹的问题,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2021-02-02
  • SpringBoot集成Redis,并自定义对象序列化操作

    SpringBoot集成Redis,并自定义对象序列化操作

    这篇文章主要介绍了SpringBoot集成Redis,并自定义对象序列化操作,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2021-06-06

最新评论