springboot项目实战 applicationEvent + EventListener 实现自定义监听器

本文详细介绍了如何在SpringBoot项目中使用`applicationEvent`和`EventListener`实现自定义监听器。通过两种方式处理事件,一是通过`EventListener`,二是通过`ApplicationListener`配合自定义事件。在模拟业务场景中,展示了如何发布事件以及异步处理事件,以达到解耦和提高系统可维护性的目的。最后,通过实例演示了在Controller中处理和异步任务处理积分逻辑的过程。
摘要由CSDN通过智能技术生成

ApplicationEvent作用说明(帮助理解):
ApplicationEvent以及Listener是Spring为我们提供的一个事件监听、订阅的实现,内部实现原理是观察者设计模式,设计初衷也是为了系统业务逻辑之间的解耦,提高可扩展性以及可维护性

自定义Event事件

import lombok.Getter;
import lombok.Setter;
import org.springframework.context.ApplicationEvent;

import java.util.Map;

@Setter
@Getter
public class MyEvent extends ApplicationEvent {
   

    private Map<String, String> map;

    public MyEvent(Object source, Map<String, String> map) {
   
        super(source);
        this.map = map;
    }
}

Event事件处理方式

第一种 通过EventListener处理

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;


@Component
@Slf4j
public class MyEventListenerDeal {
   

    @EventListener
    public void handleMyEventMap(MyEvent myEvent) {
   
        log.info("------------handleMyEvent -----------");
        // 測試  模擬真是業務的處理
        myEvent.getMap().put("city", "beijing");
    }
}

第二种通过事件ApplicationListerner加自定义的事件进行处理

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;


@Component
@Slf4j
public class MyEventListenerDeal implements ApplicationListener<MyEvent> {
   

    @Override
    public void onApplicationEvent(MyEvent myEvent) {
   
        log.info("已经监听到开始处理!!!");
        myEvent.getMap().put("city", "河南太热了!!!");
    }
}

模拟业务层进行事件发布

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

import java.util.HashMap;
import java.util.Map;

@Component
public class MyEventTriggerService {
   

    @Autowired
    private ApplicationEventPublisher applicationEventPublisher;

    public Map<String, String> triggerMap() {
   
        // 模拟实际项目业务
        Map<String, String> map = new HashMap<>();
        map.put("name", "zhangting");
        map.put("city", "nanjing");

        MyEvent myEvent = new MyEvent
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值