Spring Boot 事件监听机制完整开发指南

【Spring Boot 3】事件机制 定义事件类定义事件发布定时事件监听其中每一步都有多种方法实现,本文即是介绍开发Spring Boot应用实现事件机制的这些方法。Spring事件默认是单线程执行的,好处在于事件监听和事件发布可以使用同样的事务(Transaction)上下文;本文介绍的配置多线程执行的方法将对应用中所有的事件监听器生效,如果想控制只为其中某些监听器生效,则不需要本文中的定义,只需在需要多线程执行的事件监听器方法上添加@Async注解即可。 阅读详情

以下是关于 Spring Boot 事件监听机制 的完整开发指南,涵盖原理、生命周期、内置事件、自定义监听器、排序机制、必知监听器详解、常见问题与最佳实践,并附有带详细中文注释的标准实战示例,完全符合你对“实际开发参考价值”和“中文注释”的要求。


📜 Spring Boot 事件监听机制完整开发指南

一、事件监听机制原理(Event-Driven Architecture)

Spring 的事件机制基于 观察者模式(Observer Pattern),核心是 ApplicationEvent 与 ApplicationListener 的发布-订阅模型。

核心组件:

组件说明
ApplicationEvent所有事件的基类,代表一个“事件发生”
ApplicationListener<E extends ApplicationEvent>事件监听器接口,监听特定事件类型
ApplicationEventPublisher事件发布器,用于发布事件(Spring 容器自动注入)
ApplicationEventMulticaster事件多播器,负责将事件分发给所有匹配的监听器

✅ 原理流程:

  1. 某个组件调用 applicationEventPublisher.publishEvent(event)
  2. Spring 容器的 ApplicationEventMulticaster 查找所有注册的、能处理该事件类型的 ApplicationListener
  3. 依次调用这些监听器的 onApplicationEvent() 方法(同步阻塞,默认单线程)

二、Spring Boot 事件生命周期

Spring Boot 应用启动/关闭过程中会触发一系列内置事件,按执行顺序如下:

生命周期阶段事件类触发时机
容器初始化前ApplicationStartingEventSpringApplication.run() 刚开始执行
环境准备完成ApplicationEnvironmentPreparedEventEnvironment 准备完毕,但容器尚未创建
ApplicationContext 创建前ApplicationPreparedEventApplicationContext 已创建,但 Bean 未加载
ApplicationContext 初始化完成ContextRefreshedEvent所有 Bean 加载完成,上下文刷新完毕(最常用)
Web 服务器启动完成WebServerInitializedEvent嵌入式服务器(如 Tomcat)启动完成,端口已绑定
应用启动完成ApplicationReadyEvent应用已完全启动,可处理请求(推荐用于业务初始化)
应用关闭前ApplicationStoppingEvent用户触发关闭(如 Ctrl+C)
应用已关闭ApplicationClosedEvent应用完全退出

⚠️ 注意:ContextRefreshedEvent 在 刷新上下文时触发,若使用 @RefreshScope 或 Actuator 的 /actuator/refresh,它可能被多次触发!


三、Spring Boot 内置事件监听器(必须掌握)

以下是你在实际开发中必须了解和掌握的内置事件及其作用:

事件类作用生效时机使用建议
ApplicationReadyEvent应用完全启动完成,可对外提供服务所有 Bean 初始化完成、Web 服务器已启动、健康检查通过✅ 推荐用于初始化缓存、连接池、定时任务、注册服务发现
ContextRefreshedEvent上下文刷新完成(Bean 加载完毕)每次调用 refresh() 时触发(包括热部署)⚠️ 避免在此事件中执行耗时操作,可能重复触发
WebServerInitializedEvent嵌入式 Web 服务器(Tomcat/Jetty/Undertow)启动完成端口绑定成功后✅ 用于获取实际端口(如日志打印、健康检查)
ApplicationFailedEvent应用启动失败启动过程中抛出未捕获异常✅ 用于发送告警、记录失败原因
ApplicationStartedEvent应用已启动(但 Web 服务器可能未就绪)ApplicationContext 刷新完成,但 Web 服务器未启动⚠️ 少用,除非你不需要 Web 服务就绪
ApplicationStoppingEvent应用正在停止用户触发关闭(如 System.exit() 或 kill)✅ 用于优雅关闭连接、清理临时文件
ApplicationClosedEvent应用已关闭所有资源释放完毕✅ 用于日志归档、监控上报

✅ 开发建议:

  • 业务初始化 → 优先使用 ApplicationReadyEvent
  • 获取端口 → 使用 WebServerInitializedEvent
  • 异常监控 → 监听 ApplicationFailedEvent
  • 优雅关闭 → 监听 ApplicationStoppingEvent

四、自定义事件监听器开发(标准写法)

步骤 1:定义自定义事件(继承 ApplicationEvent)

import org.springframework.context.ApplicationEvent;

/**
 * 自定义事件:用户注册成功事件
 * 该事件携带用户ID和注册时间,供后续模块(如发邮件、积分奖励)消费
 */
public class UserRegisteredEvent extends ApplicationEvent {

    private final Long userId;           // 用户ID
    private final String email;          // 用户邮箱
    private final long registerTime;     // 注册时间戳(毫秒)

    /**
     * 构造函数:必须调用父类构造器,传入事件源(通常是发布者)
     * @param source 事件源对象(通常为发布该事件的组件,如 UserService)
     * @param userId 用户ID
     * @param email 用户邮箱
     */
    public UserRegisteredEvent(Object source, Long userId, String email) {
        super(source); // 必须调用,Spring 用它追踪事件来源
        this.userId = userId;
        this.email = email;
        this.registerTime = System.currentTimeMillis();
    }

    // Getter 方法,供监听器使用
    public Long getUserId() {
        return userId;
    }

    public String getEmail() {
        return email;
    }

    public long getRegisterTime() {
        return registerTime;
    }

    @Override
    public String toString() {
        return "UserRegisteredEvent{userId=" + userId + ", email='" + email + "', registerTime=" + registerTime + '}';
    }
}

步骤 2:编写事件监听器(实现 ApplicationListener)

import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * 监听用户注册成功事件
 * 作用:在用户注册后,自动发送欢迎邮件
 * 注意:此监听器是 Spring 管理的 Bean,自动注册到事件总线
 */
@Component
public class UserRegisteredEventListener implements ApplicationListener<UserRegisteredEvent> {

    private static final Logger log = LoggerFactory.getLogger(UserRegisteredEventListener.class);

    /**
     * Spring 容器在发布 UserRegisteredEvent 时,自动调用此方法
     * 该方法是同步执行的,阻塞发布者线程,因此应避免耗时操作
     * 如需异步,可结合 @Async 或消息队列
     *
     * @param event 用户注册事件对象,包含用户ID、邮箱等信息
     */
    @Override
    public void onApplicationEvent(UserRegisteredEvent event) {
        // 打印事件来源(如 UserService 实例)
        log.info("【事件监听】收到用户注册事件,来自: {}", event.getSource().getClass().getSimpleName());

        // 提取事件数据
        Long userId = event.getUserId();
        String email = event.getEmail();
        long registerTime = event.getRegisterTime();

        // 格式化时间
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String formattedTime = LocalDateTime.ofInstant(java.time.Instant.ofEpochMilli(registerTime), 
                java.time.ZoneId.systemDefault()).format(formatter);

        // 模拟发送欢迎邮件(实际项目中应调用邮件服务)
        log.info("✅ 正在为用户 ID={},邮箱={} 发送欢迎邮件...(模拟)", userId, email);
        log.info("⏰ 注册时间: {}", formattedTime);

        // 可在此处调用邮件服务、积分服务、短信服务等
        // sendWelcomeEmail(email);
        // awardPoints(userId, 100);

        log.info("📧 欢迎邮件发送任务已提交(异步执行)");
    }
}

步骤 3:在服务中发布事件(触发监听器)

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Service;

/**
 * 用户服务:负责用户注册逻辑
 * 在注册成功后,发布自定义事件,解耦后续业务逻辑
 */
@Service
public class UserService {

    @Autowired
    private ApplicationEventPublisher eventPublisher; // Spring 自动注入事件发布器

    /**
     * 用户注册方法
     * 核心:注册成功后,发布事件,而非直接调用邮件服务
     * 实现了业务逻辑与通知逻辑的解耦
     *
     * @param email 用户邮箱
     * @return 注册结果
     */
    public String registerUser(String email) {
        // 1. 校验邮箱格式
        if (email == null || !email.contains("@")) {
            throw new IllegalArgumentException("邮箱格式不合法");
        }

        // 2. 模拟保存用户到数据库(伪代码)
        Long userId = saveUserToDatabase(email); // 假设返回自增ID

        // 3. ✅ 发布事件:通知其他模块“用户已注册”
        // 此处不直接调用 EmailService,而是发布事件,实现松耦合
        eventPublisher.publishEvent(new UserRegisteredEvent(this, userId, email));

        // 4. 返回成功
        return "注册成功,欢迎加入我们!";
    }

    // 模拟保存用户
    private Long saveUserToDatabase(String email) {
        // 模拟数据库插入,返回用户ID
        return 1001L;
    }
}

步骤 4:测试事件是否生效(Controller 触发)

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * 测试控制器:通过 HTTP 请求触发用户注册,从而发布事件
 */
@RestController
public class TestEventController {

    @Autowired
    private UserService userService;

    /**
     * 访问:GET /test/register?email=test@example.com
     * 触发事件监听器,控制台将输出监听日志
     */
    @GetMapping("/test/register")
    public String register(@RequestParam String email) {
        return userService.registerUser(email);
    }
}

✅ 运行效果(控制台输出)

2025-10-14 10:00:00 [http-nio-8080-exec-1] INFO  c.s.UserService - 注册用户:test@example.com
2025-10-14 10:00:00 [http-nio-8080-exec-1] INFO  c.s.UserRegisteredEventListener - 【事件监听】收到用户注册事件,来自: UserService
2025-10-14 10:00:00 [http-nio-8080-exec-1] INFO  c.s.UserRegisteredEventListener - ✅ 正在为用户 ID=1001,邮箱=test@example.com 发送欢迎邮件...(模拟)
2025-10-14 10:00:00 [http-nio-8080-exec-1] INFO  c.s.UserRegisteredEventListener - ⏰ 注册时间: 2025-10-14 10:00:00
2025-10-14 10:00:00 [http-nio-8080-exec-1] INFO  c.s.UserRegisteredEventListener - 📧 欢迎邮件发送任务已提交(异步执行)
2025-10-14 10:00:00 [http-nio-8080-exec-1] INFO  c.s.TestEventController - 返回:注册成功,欢迎加入我们!

五、事件监听器排序(@Order 注解)

多个监听器监听同一事件时,执行顺序默认不确定。如需控制顺序(如先更新缓存,再发消息),使用 @Order 注解。

@Component
@Order(1) // 数字越小,优先级越高
public class CacheUpdateListener implements ApplicationListener<UserRegisteredEvent> {
    @Override
    public void onApplicationEvent(UserRegisteredEvent event) {
        log.info("【优先级1】更新用户缓存:{}", event.getUserId());
    }
}

@Component
@Order(2)
public class NotificationListener implements ApplicationListener<UserRegisteredEvent> {
    @Override
    public void onApplicationEvent(UserRegisteredEvent event) {
        log.info("【优先级2】发送通知:{}", event.getEmail());
    }
}

✅ 最佳实践:

  • 使用 @Order(Ordered.HIGHEST_PRECEDENCE) 表示最高优先级
  • 使用 @Order(Ordered.LOWEST_PRECEDENCE) 表示最低优先级
  • 优先级建议以 10 为单位递增,留出扩展空间

六、异步事件监听(避免阻塞主线程)

默认事件是同步阻塞的。若监听器内有网络调用、IO 操作,会导致发布者线程等待。

✅ 解决方案:使用 @Async

步骤 1:启用异步支持(配置类)
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;

/**
 * 启用 Spring 异步支持
 */
@EnableAsync // 开启异步方法支持
@Configuration
public class AsyncConfig {
    // 可在此配置线程池,如 @Bean public TaskExecutor taskExecutor() {...}
}
步骤 2:监听器方法标记为异步
@Component
public class AsyncEmailListener implements ApplicationListener<UserRegisteredEvent> {

    private static final Logger log = LoggerFactory.getLogger(AsyncEmailListener.class);

    /**
     * 此方法将异步执行,不阻塞主线程
     * 注意:@Async 不能用于 private 方法,且必须在 Spring 管理的 Bean 中
     */
    @Async // ✅ 标记为异步执行
    @Override
    public void onApplicationEvent(UserRegisteredEvent event) {
        log.info("🚀 异步发送欢迎邮件(不会阻塞注册流程)到: {}", event.getEmail());

        // 模拟网络延迟(如调用 SMTP 服务)
        try {
            Thread.sleep(3000); // 模拟耗时操作
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }

        log.info("✅ 异步邮件发送完成,用户ID: {}", event.getUserId());
    }
}

⚠️ 注意事项:

  • @Async 方法必须在 Spring Bean 中,且不能是 private
  • 不能在同一个类中调用 @Async 方法(会被 Spring 代理忽略)
  • 异步监听器失败不会影响主流程,但建议添加异常处理(@Async 默认不抛异常)

七、开发过程中常见问题与注意事项

问题原因解决方案
监听器未生效未加 @Component 或未在 Spring 扫描路径下确保监听器类上有 @Component,或被 @Configuration 类 @Bean 注册
事件被重复触发ContextRefreshedEvent 在热部署/Actuator刷新时多次触发避免在此事件中做初始化,改用 ApplicationReadyEvent
监听器执行慢导致应用启动卡住同步监听器中执行了数据库查询、HTTP 请求改为 @Async 异步处理,或使用消息队列(RabbitMQ/Kafka)
事件顺序混乱多个监听器无排序使用 @Order 明确指定执行顺序
监听器抛异常导致发布者失败默认监听器异常会传播使用 @EventListener + @Async + @ExceptionHandler 包装,或捕获异常
监听器内存泄漏监听器持有大对象或未注销确保监听器是单例,避免持有非静态内部类引用

八、最佳实践总结(开发必看)

原则说明
✅ 优先使用 ApplicationReadyEvent保证所有 Bean、Web 服务、数据库连接都就绪后再执行初始化
✅ 事件应轻量、无副作用事件只通知,不执行核心业务,避免耦合
✅ 耗时操作异步化邮件、短信、日志写入等使用 @Async 或消息队列
✅ 事件命名清晰如 OrderPaidEvent、ProductStockUpdatedEvent,避免 MyEvent
✅ 避免循环事件事件 A 触发事件 B,B 又触发 A,导致栈溢出
✅ 使用 @EventListener 替代 ApplicationListener(推荐)更简洁,支持泛型,支持条件过滤

✅ 推荐写法:使用 @EventListener(更现代)

@Component
public class EventListenerDemo {

    @EventListener
    public void handleUserRegistered(UserRegisteredEvent event) {
        log.info("【@EventListener】监听到用户注册: {}", event.getUserId());
    }

    // 支持条件过滤
    @EventListener(condition = "#event.userId > 1000")
    public void handleHighValueUser(UserRegisteredEvent event) {
        log.info("高价值用户注册: {}", event.getUserId());
    }

    // 支持异步
    @Async
    @EventListener
    public void sendWelcomeEmail(UserRegisteredEvent event) {
        // 异步发送邮件
    }
}

💡 @EventListener 是 Spring 4.2+ 推荐方式,比实现接口更简洁、灵活,强烈推荐在新项目中使用。


九、总结:你必须掌握的监听器清单

事件是否必须掌握作用推荐使用场景
ApplicationReadyEvent✅ 必须应用完全启动初始化缓存、定时任务、注册服务
WebServerInitializedEvent✅ 必须Web 服务器启动完成获取实际端口、打印启动日志
ApplicationFailedEvent✅ 必须启动失败发送告警、记录错误堆栈
ApplicationStoppingEvent✅ 必须应用即将关闭优雅关闭数据库连接、清理临时文件
ContextRefreshedEvent⚠️ 谨慎使用上下文刷新避免在此做初始化,易重复触发
ApplicationClosedEvent✅ 建议应用完全关闭上报监控、归档日志

✅ 最终建议

  • 新项目推荐使用 @EventListener + @Async,代码更简洁、可读性更强。
  • 事件是解耦利器,但不要滥用,避免“事件风暴”。
  • 生产环境务必监控 ApplicationFailedEvent,它是系统健康的第一道防线。
  • 事件不是 RPC,不要通过事件传递复杂业务参数,建议使用 ID + 查询。

解释Spring Boot中事件监听器的作用。 首先,我们可以定义一个。 阅读详情

相关推荐

Spring Boot 监听器详解

SpringApplicationRunListener 是SpringApplication 的运行监听器,提供Spring Boot启动时各个运行状态的监听,可以在应用程序启动的时候执行一些自定义操作或记录一些信息。SpringApplicationRunListener 在run中加载。是Spring 提供的上下文监听器,可用于监听指定感兴趣的事件。最后还是用一张图来总结整个流程作者其他文章:Prometheus 系列文章Prometheus 的介绍和安装。

分享技术干货和灵感、推荐新书和好玩的项目、分享Java面试题 8820

Springboot事件监听

Springboot事件监听

一名编程小白的Java学习日志 3304

SpringBoot 事件发布监听机制使用、分析、注意点 (一篇到位)

事件发布监听机制使用、分析、注意点

默默不代表沉默 1万+

【Java】SpringBoot实现事件监听(异步执行)

SpringBoot实现事件监听(异步执行)-源码测试

m0_64210833的博客 6266

(一)SpringBoot事件发布与监听

(一)SpringBoot事件发布与监听

专搞技术的小兔子 351

GPU运维工程师入门指南 (第九篇): 高性能网络 - InfiniBand与RDMA技术

本文介绍了支撑AI分布式训练的高性能网络技术InfiniBand和RDMA。传统TCP/IP网络因内核开销和内存拷贝成为性能瓶颈,而InfiniBand提供高带宽、低延迟的专用网络,RDMA则通过内核旁路和零拷贝技术实现节点间内存直接访问,显著提升通信效率。特别介绍了GPUDirect RDMA技术,使GPU显存可直接通信。文章还列举了运维人员在部署这些技术时需要考虑的硬件、驱动、配置和监控等关键点。这些技术共同构成了支撑大规模AI集群的"数据高速公路",为后续讨论存储性能瓶颈奠定了基础

weixin_42587823的博客 1105

Spring Boot 事件监听机制深度解析

Spring Boot 事件监听机制基于 Spring 框架的事件发布/订阅模型。在这个模型中,事件源(即事件的发布者)会在特定事件发生时发布一个事件对象,而监听器(即事件的订阅者)则会接收到这个事件对象并执行相应的操作。Spring Boot 提供了一套完整的 API 来实现这个模型,包括类、接口以及注解等。通过以上介绍,我们可以发现 Spring Boot 中的事件监听机制非常简单易用。我们只需要创建一个事件类、一个事件监听器以及在适当的地方发布事件即可。

weixin_52721608的博客 2191

解锁全志T113-i隐藏技能:用RISC-V核跑实时系统比STM32还稳?

本文深入探讨了全志T113-i SoC的异构架构潜力,重点解析如何利用其内置的玄铁C906 RISC-V核心独立运行实时系统。通过对比传统MCU与Linux方案,文章提供了从RISC-V核心启动、FreeRTOS移植到与Linux主核进行高效异构通信的完整实战指南,为工控等需要兼顾丰富应用与硬实时控制的场景提供了高集成度的单芯片解决方案。

ansible6ops的博客 497

Spring Boot事件监听机制

当某件事情发生时,通知对此感兴趣的各方进行响应。报纸订阅:有新报纸时,报社会通知所有订阅者交通信号:红灯亮起时,车辆和行人会做出相应反应手机通知:收到消息时,手机会发出提示音在软件开发中,这种模式被称为观察者模式(Observer Pattern),也称为发布-订阅模式。事件触发时机ApplicationContext初始化或刷新完成时ApplicationContext启动时(调用start()方法)ApplicationContext停止时(调用stop()方法)

A1234543211232的博客 774

matlab锅炉 pid仿真,基于Matlab锅炉仿真.doc

基于Matlab锅炉仿真内蒙古科技大学MATLAB课程设计任务书2012题 目:锅炉汽包水位控制系统学生姓名:林三彪学 号:0967112127专 业:测控技术与仪器班 级:2009-1指导教师:梁 丽摘 要锅炉是化工、炼油、发电、造纸和制糖等工业生产过程中必不可少的重要动力设备。锅炉往往成了不少工厂不可缺少的一部分,因而,对锅炉设备中的自动控制系统进行分析研究是必要的...

weixin_29133981的博客 1101

【Tessent Shell Users Manual】【Ch3】Design Introspection and Editing(未完待续)

Tessent Shell 提供了一系列用于检查(examining/introspecting)和编辑design的命令。

Tranquil_ovo的博客 1738

Spring Boot 事件监听机制工作原理

总结:Spring Boot 事件监听机制工作原理其实和 Spring 的事件监听机制原理一样,Spring Boot 只是通过自动配置简化了一些复杂的配置而已,如果我们熟读 Spring 的源码,那对 Spring Boot 的源码解读是有极大帮助的,Spring Boot 很多功能都是基于 Spring 的,最后本篇关于 Spring Boot 事件监听机制工作原理的分享,希望可以帮助到需要的小伙伴。事件监听器需要注册到事件发布器中,那事件监听器是设么时候注册的?如有不正确的地方请各位指出纠正。

weixin_42118323的博客 2056

ADS1299EEG-FE评估板PCB与BOM深度解析:高精度生物电信号采集硬件设计实战

在模拟电路与混合信号系统设计中,PCB布局和物料选型是决定系统性能上限的关键环节,尤其在高精度数据采集领域。其核心原理在于通过精心的电源分配、信号链规划和接地策略,将芯片数据手册的理论指标转化为板载的实际性能,这直接关系到系统的信噪比与测量精度。对于EEG/ECG这类微伏级生物电信号采集,任何布局不当或物料参数不匹配都可能导致噪声淹没有用信号。因此,深入剖析一个经过验证的参考设计——例如围绕TI ADS1299芯片构建的评估板——具有极高的工程价值。它能具体展示如何在高性能ADC应用中,通过四层板层叠设计、

weixin_29164497的博客 302

在Spring中使用监听器以及事件监听机制

在Spring中使用监听器以及事件监听机制

进击的豌豆的博客 1583

量化投资之工具篇一:Backtrader从入门到精通(1)-手把手教你零基础实现一个策略案例

Backtrader是重要的量化框架,本文记录学习该框架的笔记,内容主要基于Backtrader的网站指导文档。虽然该框架目前用于量化投资领域,但是可以作为数据处理的基本架构,进行改造后用于各种数据的处理,尤其适用于对原始数据处理完成后应用一定的策略进行预测以及可视化处理。 1、简介 Backtrader的特点,就是两点: 1、易于使用; 2、参见第1条。 那么如何使用Backtrader呢?比把大象装进冰箱复杂点,一共4步: 创建一个Cerebro引擎: 加入一个Strategy...

仓鼠王的博客 5万+

Raspberry Pi Pico + Inmp441麦克风(Pio模拟I2s)<2>

摘要:本文介绍了在Raspberry Pi Pico上使用PIO(Programmable I/O)接收I2S数字麦克风音频数据并保存为WAV文件的方法。项目采用双PIO状态机设计,一个生成I2S时钟信号(WS+SCK),另一个接收24位左声道数据并转换为16位格式。文章详细说明了接线方式、参数设置、WAV文件头构造、PIO汇编程序实现以及数据转换处理流程。项目在MicroPython环境下实现16kHz采样率、6秒时长录音,具有时序精确、稳定可靠的特性,并提供了进一步拓展的可能性,如双声道支持、实时频谱分

技术需要沉淀,需要碰撞。 666

Spring Boot事件机制详解

事件驱动架构(Event-Driven Architecture, EDA)是一种软件设计模式,其中系统组件通过事件的发布与订阅进行通信。在Spring Boot中,事件机制为应用程序提供了松耦合的组件间通信方式,使得发布者无需关心谁在监听,监听者也无需了解事件来源

AWen_Jack的博客 1874

【产品经理修炼之道】-如何搭建企业级账务系统?

笔者公司的业务模式具有一定的独特性,不同于我们常见的市面上供应链类公司的进销存模式。公司主要为各大银行和金融机构提供信贷领域的风控服务,客户主要通过请求公司的数据产品接口产生费用,可以简单地理解为请求一次接口收费0.5元,一个月若是有1w人请求同一个接口则公司需要收费5000元。

xiaoli8748的专栏 5410

Spring Boot 机制三: ApplicationContext 生命周期与事件机制源码解析

Component@OverrideSystem.out.println("收到事件: " + event.getMessage());事件触发阶段用途SpringApplication.run() 开始日志/监控Environment 初始化完成自定义属性处理ApplicationContext 创建完成注册 Beanrefresh 前容器准备完成refresh 后Bean 已初始化应用完全启动启动后逻辑启动失败异常处理。

Java、Python、AI、前沿技术等领域的技术总结和经验分享。 5601

WINCC7.3破解文件

WINCC7.3硬件够破解文件,有需要的下载!WINCC7.3硬件够破解文件,有需要的下载!

最新的sdio 4.0 spec 协议标准 带书签 高清完整PDF版

Part-E1-SDIO-Specification-Ver4.00-Final-120220.pdf:最新的sdio 4.0 spec 协议标准 带书签 高清完整PDF版,包括SDIO 接口的外设,SDIO 接口官方协议等。

Spring Boot 事件监听机制实战【自定义 Spring Boot 事件监听】

事件监听器实现了 ApplicationLister 接口,泛型为 ApplicationEvent,因为要监听事件,所以必须按照 Spring 的规则来,onApplicationEvent 方法就是监听到的事件,在这里可以完成业务逻辑处理,因为事件监听器需要加入Spring IOC 容器中才能生效,因此 MyListener 使用了 @Component 注解。上一篇我们分析了 Spring Boot 事件监听的原理,本篇我们来自定义实现自己的监听器。欢迎提出建议及对错误的地方指出纠正。

weixin_42118323的博客 847

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

Spring Boot 事件监听机制详解:ApplicationListener 的原理与实践

本文详细解析了Spring Boot中的事件监听机制,重点介绍了ApplicationListener接口的演进过程,从基础接口到增强型SmartApplicationListener和GenericApplicationListener。深入剖析了Spring Boot内置的核心监听器,如配置文件加载、日志系统初始化和字符编码校验等关键功能。通过自定义事件监听器的代码示例,展示了如何实现应用启动后的健康检查通知。最后针对常见问题提供了排查方案,帮助开发者更好地理解和应用这一重要机制。

刘一说的IT专栏 577

文档:亲测可用解决vnc灰屏,黑屏,鼠标大黑叉情况

主要解决vnc-viewer灰屏,黑屏,鼠标大黑叉等现象,详细见文档。

Spring Boot 事件机制详解

Spring Boot 事件机制详解

嗨,欢迎来到我的 CSDN 博客小天地!一名深耕多年的技术发烧友。在这里,我将把日常工作中积累的宝贵经验,从复杂架构设计的精妙之处,到代码优化的实战技巧,毫无保留地分享给大家。 7252

Spring Boot事件监听

1.Spring的事件是为Bena和Bean之间的消息通信提供支持,当一个Bean处理完成一个任务之后,会通知另一个Bean并让其进行相应的后续处理,这时候需要让里一个Bean监听当前Bean所发送的一个事件。 Spring Boot中定义事件的流程如下图: 事件监听器的作用是指定要监听哪一个事件。 import org.springframework.context.ApplicationEvent; /** * 定义事件 * @author Administrator * */ public

qq_40091033的博客 379

Spring Boot 事件监听机制与 EventPublishingRunListener

在金融或证券级系统中,数据库账号密码和第三方 API 密钥严禁在中明文存储。我们可以通过自定义在环境变量准备就绪的第一时间,对所有以ENC(...)// 必须提供符合规范的双参构造函数@Override// 优先级必须高于普通的业务监听器@Overridelog.info(">>> [安全治理] 触发环境就绪事件,开始扫描并解密敏感配置属性...");// 遍历所有 PropertySource 查找 ENC() 格式密文。

alex_goden的博客 204
上一篇: RestClient:Spring Web 同步 HTTP 客户端权威说明文档
下一篇: Spring Boot 事件机制四大核心应用场景实践指南
龙茶清欢
博客等级 码龄7年 3720粉丝 375原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

龙茶清欢

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值
⌂ 换网址