Spring或SpringBoot项目随项目启动而启动线程执行特定任务的方法

简介: 项目启动,你是否有需求需要某个任务能随着项目启动就去执行某个任务呢?

当然方法不止一种    如注解:@PostConstruct   或者springBoot项目实现 ApplicationRunner


importcom.gpyh.gms.server.service.goods.GoodsInfoSynchService;importorg.slf4j.Logger;
importorg.slf4j.LoggerFactory;
importorg.springframework.beans.factory.annotation.Autowired;
importorg.springframework.context.ApplicationListener;
importorg.springframework.context.annotation.DependsOn;
importorg.springframework.context.event.ContextRefreshedEvent;
importorg.springframework.stereotype.Component;
importjava.util.concurrent.ExecutorService;
importjava.util.concurrent.Executors;
@Component//@DependsOn({"需要依赖的类(启动的线程,需要在这个类后面完成初始化可添加)"})publicclassMyApplicationListenerimplementsApplicationListener<ContextRefreshedEvent> {
privatestaticfinalLoggerlogger=LoggerFactory.getLogger(MyApplicationListener.class);
@AutowiredprivateGoodsInfoSynchServicegoodsInfoSynchService;
@OverridepublicvoidonApplicationEvent(ContextRefreshedEventevent) {
// 创建单线程池ExecutorServiceexecutor=Executors.newSingleThreadExecutor();
logger.info("线程启动监控");
executor.execute(()->**需要执行的任务**);
    }
}

importorg.springframework.stereotype.Component;
importjavax.annotation.PostConstruct;
@ComponentpublicclassQueueMonitor {
@PostConstructpublicvoidstartQueueMonitor() {
Threadthread=newThread(newYourQueueMonitorRunnable());
thread.start();
    }
privateclassYourQueueMonitorRunnableimplementsRunnable {
@Overridepublicvoidrun() {
// 监控队列的逻辑        }
    }
}
目录
相关文章
|
7月前
|
XML Java 应用服务中间件
【SpringBoot(一)】Spring的认知、容器功能讲解与自动装配原理的入门,带你熟悉Springboot中基本的注解使用
SpringBoot专栏开篇第一章,讲述认识SpringBoot、Bean容器功能的讲解、自动装配原理的入门,还有其他常用的Springboot注解!如果想要了解SpringBoot,那么就进来看看吧!
732 2
|
8月前
|
人工智能 Java 机器人
基于Spring AI Alibaba + Spring Boot + Ollama搭建本地AI对话机器人API
Spring AI Alibaba集成Ollama,基于Java构建本地大模型应用,支持流式对话、knife4j接口可视化,实现高隐私、免API密钥的离线AI服务。
6953 2
基于Spring AI Alibaba + Spring Boot + Ollama搭建本地AI对话机器人API
存储 JSON Java
912 0
|
9月前
|
监控 Java API
Spring Boot 3.2 结合 Spring Cloud 微服务架构实操指南 现代分布式应用系统构建实战教程
Spring Boot 3.2 + Spring Cloud 2023.0 微服务架构实践摘要 本文基于Spring Boot 3.2.5和Spring Cloud 2023.0.1最新稳定版本,演示现代微服务架构的构建过程。主要内容包括: 技术栈选择:采用Spring Cloud Netflix Eureka 4.1.0作为服务注册中心,Resilience4j 2.1.0替代Hystrix实现熔断机制,配合OpenFeign和Gateway等组件。 核心实操步骤: 搭建Eureka注册中心服务 构建商品
1393 3
|
10月前
|
Java 测试技术 Spring
简单学Spring Boot | 博客项目的测试
本内容介绍了基于Spring Boot的博客项目测试实践,重点在于通过测试驱动开发(TDD)优化服务层代码,提升代码质量和功能可靠性。案例详细展示了如何为PostService类编写测试用例、运行测试并根据反馈优化功能代码,包括两次优化过程。通过TDD流程,确保每项功能经过严格验证,增强代码可维护性与系统稳定性。
381 0
|
10月前
|
存储 Java 数据库连接
简单学Spring Boot | 博客项目的三层架构重构
本案例通过采用三层架构(数据访问层、业务逻辑层、表现层)重构项目,解决了集中式开发导致的代码臃肿问题。各层职责清晰,结合依赖注入实现解耦,提升了系统的可维护性、可测试性和可扩展性,为后续接入真实数据库奠定基础。
787 0
|
10月前
|
Java 关系型数据库 数据库连接
Spring Boot项目集成MyBatis Plus操作PostgreSQL全解析
集成 Spring Boot、PostgreSQL 和 MyBatis Plus 的步骤与 MyBatis 类似,只不过在 MyBatis Plus 中提供了更多的便利功能,如自动生成 SQL、分页查询、Wrapper 查询等。
1012 2
|
10月前
|
Java 应用服务中间件 Maven
第01课:Spring Boot开发环境搭建和项目启动
第01课:Spring Boot开发环境搭建和项目启动
3217 0