当前位置: 首页 > news >正文

SpringBoot项目启动后自动执行方法

前言

在SpringBoot项目中,当项目启动后想自动执行某一个方法或任务有多种方式,比如:使用 CommandLineRunner、ApplicationRunner、@PostConstruct、ApplicationListener

本文讲解使用 ApplicationListener ,使 SpringBoot 项目启动后自动运行 onApplicationEvent 方法。

一、实现

实现ApplicationListener接口并监听ApplicationStartedEvent事件,这样你 onApplicationEvent 方法中的的逻辑将在应用启动后被触发。

示例1

下面的代码将在项目启动后自动的打印 “你好!”

import org.springframework.boot.context.event.ApplicationStartedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Service;@Service
public class AutoRun implements ApplicationListener<ApplicationStartedEvent> {@Overridepublic void onApplicationEvent(ApplicationStartedEvent event) {System.out.println("你好!");}}

示例2

下面的代码将在项目启动后自动运行 onApplicationEvent 方法,该方法里调用线程池每10秒 打印一次 “你好!”

@Configuration
public class TaskExecutorConfig {@Bean(name = "taskExecutor")public ThreadPoolTaskExecutor taskExecutor() {ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();executor.setCorePoolSize(5);executor.setMaxPoolSize(10);executor.setQueueCapacity(25);executor.initialize();return executor;}
}
@Component
public class AutoTask {public void print() {System.out.println("你好!");}
}
@Service
public class AutoRun implements ApplicationListener<ApplicationStartedEvent> {@Qualifier("taskExecutor")@Autowiredprivate ThreadPoolTaskExecutor taskExecutor;@Autowiredprivate AutoTask autoTask;@Overridepublic void onApplicationEvent(ApplicationStartedEvent event) {taskExecutor.execute(() -> {while (!taskExecutor.getThreadPoolExecutor().isShutdown()) {try {Thread.sleep(10000);autoTask.print();} catch (InterruptedException e) {e.printStackTrace();}}});}}

http://www.mrgr.cn/news/11272.html

相关文章:

  • XML 数据格式介绍及其应用
  • 【区块链 + 智慧文旅】虎彩小虎智数营销平台 | FISCO BCOS应用案例
  • TLB的刷新方式--linux 2.4
  • 分意图 Prompt 调试、后置判别改写、RLHF 缓解大模型生成可控性
  • CRMEB-PHP多商户版安装系统配置清单
  • 知识付费小程序搭建
  • C/C++开发神器CLion全新发布v2024.2——更适用于嵌入式开发
  • 给自己复盘的随想录笔记-链表
  • C#多项目统一版本号
  • ssrf实现
  • Docker Compose构建及运行多容器利器
  • vue devserver proxy设置跨域详解
  • GPT-SovitsV2,支持多语种,多音字优化,更好的音色,ZeroShot(WIN/MAC)
  • Spring Task定时任务
  • 采用ELK搭建日志平台,Elasticsearch安装
  • 基于R语言遥感随机森林建模与空间预测
  • Vue中使用el-table自定义序号翻页后又从1开始没有连续
  • [Day 61] 區塊鏈與人工智能的聯動應用:理論、技術與實踐
  • 三层链路聚合
  • 【本社翻译】Unity官方XR开发电子书