Spring Boot项目启动时执行指定的方法

项目场景:

本文介绍Spring Boot项目启动时执行指定的方法两种常用方式和他们之间的区别。


实现方案:

方式一:使用注解@PostConstruct

java 复制代码
@Component
public class PostConstructTest {
    @PostConstruct
    public void postConstruct() {
		System.out.println("启动时自动执行  @PostConstruct 注解方法");
    }
}

优点: 简单方便,加上一个注解就行了。

缺点:如果@PostConstruct方法内的逻辑处理时间较长,就会增加SpringBoot应用初始化Bean的时间,进而增加应用启动的时间。因为只有在Bean初始化完成后,SpringBoot应用才会打开端口提供服务,所以在此之前,应用不可访问。

建议:轻量的逻辑可放在Bean的@PostConstruct方法中,耗时长的逻辑如果放在@PostConstruct方法中,可使用@Async异步方法。

使用异步代码示例:

java 复制代码
@Service
public class TestService {
 
    @Async("testAsync")  //指定线程池
    public void test() {
        System.out.println("------------------------异步方法开始 " + Thread.currentThread().getName());
        try {
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("----------------异步方法执行完了" + Thread.currentThread().getName());
    }
}
java 复制代码
@Component
public class PostConstructTest {

	@Autowired
    private TestService testService;
	
    @PostConstruct
    public void postConstruct() {
		System.out.println("启动时自动执行  @PostConstruct 注解方法");
		testService.test();
    }
}

Spring Boot中多个PostConstruct注解执行顺序控制_多个postconstruct执行顺序-CSDN博客


方式二:实现CommandLineRunner接口

java 复制代码
@Component
public class CommandLineRunnerImpl implements CommandLineRunner {

    @Override
    public void run(String... args) throws Exception {
		System.out.println("启动时自动执行 CommandLineRunner 的 run 方法");
    }
}

优点: 项目已经初始化完毕,才会执行方法,所以不用等这个方法执行完,就可以正常提供服务了。

缺点:暂未发现。

相关推荐
霸道流氓气质2 小时前
领域驱动设计(DDD)在 Spring Boot 微服务中的实践指南
运维·spring boot·微服务
于先生吖2 小时前
SpringBoot对接大模型开发AI命理测算系统:八字排盘与AI解析接口源码全解
人工智能·spring boot·后端
Flittly3 小时前
【AgentScope Java新手村系列】(10)实战-多Agent天气助手
java·spring boot·spring
星落zx5 小时前
Spring Boot 多模型集成:优雅调用全球主流大模型
人工智能·spring boot·chatgpt
一杯奶茶¥5 小时前
水果销售网站 CRM客户信息管理系统 超市管理系 酒店管理系统 健身房管理系统 在线音乐网站 校园招聘系统
java·vue.js·spring boot·mysql·spring·java项目
进阶的小名6 小时前
Spring Boot SSE + Nginx 配置:解决 EventSource 不实时返回、连接超时、流式响应被缓冲问题
spring boot·后端·nginx
我登哥MVP7 小时前
SpringCloud Alibaba 核心组件解析:服务链路追踪
java·spring boot·后端·spring·spring cloud·java-ee·maven
范什么特西8 小时前
Spring boot细节
java·spring boot·后端
java1234_小锋8 小时前
请描述 Spring Boot 的启动流程,包括 SpringApplication 的初始化和 run 方法的核心步骤。
java·数据库·spring boot