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

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

缺点:暂未发现。

相关推荐
无人不xiao1 小时前
若依 springBoot 配置国际化
spring boot
JosieBook2 小时前
【SpringBoot】32 核心功能 - 单元测试 - JUnit5 单元测试中的嵌套测试与参数化测试详解
spring boot·单元测试·log4j
小坏讲微服务2 小时前
Nginx集群与SpringCloud Gateway集成Nacos的配置指南
spring boot·nginx·spring cloud·gateway
计算机学姐3 小时前
基于SpringBoot的新闻管理系统【协同过滤推荐算法+可视化统计】
java·vue.js·spring boot·后端·spring·mybatis·推荐算法
一 乐3 小时前
远程在线诊疗|在线诊疗|基于java和小程序的在线诊疗系统小程序设计与实现(源码+数据库+文档)
java·数据库·vue.js·spring boot·后端·小程序
serendipity_hky3 小时前
【微服务 - easy视频 | day04】Seata解决分布式事务
java·spring boot·分布式·spring cloud·微服务·架构
大菠萝学姐4 小时前
基于springboot的旅游攻略网站设计与实现
前端·javascript·vue.js·spring boot·后端·spring·旅游
q_19132846955 小时前
基于SpringBoot+Vue2的美食菜谱美食分享平台
java·spring boot·后端·计算机·毕业设计·美食
刘一说6 小时前
Spring Boot 中的定时任务:从基础调度到高可用实践
spring boot·后端·wpf
小坏讲微服务6 小时前
使用 Spring Cloud Gateway 实现集群
java·spring boot·分布式·后端·spring cloud·中间件·gateway