栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

【SpringBoot】69、SpringBoot中事件发布与监听实现

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

【SpringBoot】69、SpringBoot中事件发布与监听实现

1、简介

事件的发布监听机制类似于观察者模式,利用事件的监听机制可以实现业务的发起与业务的处理解耦,更能体现单一职责原则,例如:新用户注册,我们需要发送邮件通知用户,触发了注册事件,监听者就能监听到注册事件,进行后续操作,事件发布与监听一般需要三步:

  • 1、定义事件
  • 2、发布事件
  • 3、监听事件
2、事件定义
import org.springframework.context.ApplicationEvent;


public class UserRegisterEvent extends ApplicationEvent {

    
    private Long userId;

    public UserRegisterEvent(Object source, Long userId) {
        super(source);
        this.userId = userId;
    }

    public Long getUserId() {
        return userId;
    }

    public void setUserId(Long userId) {
        this.userId = userId;
    }
}

我们定义了一个用户注册的事件,并传递了参数为用户的id

3、事件发布 3.1 Spring 上下文工具类
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;


@Slf4j
@Service
@Lazy(false)
public class SpringContextUtil implements ApplicationContextAware, DisposableBean {

    private static ApplicationContext applicationContext = null;

    
    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) {
        SpringContextUtil.applicationContext = applicationContext;
    }

    
    public static void publishEvent(ApplicationEvent event) {
        getApplicationContext().publishEvent(event);
    }

    
    @Override
    @SneakyThrows
    public void destroy() {
        SpringContextUtil.clearHolder();
    }

    
    public static void clearHolder() {
        if (log.isDebugEnabled()) {
            log.debug("清除SpringContextHolder中的ApplicationContext:" + applicationContext);
        }
        applicationContext = null;
    }
}

我们基于 Spring 的事件发布与监听,需要用到 Spring 的上下文对象,特此有了该工具类

3.2 事件发布
// 发布用户注册事件
SpringContextUtil.publishEvent(new UserRegisterEvent(this, userId));
4、事件监听
import com.asurplus.common.event.UserRegisterEvent;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;


@Component
public class UserRegisterEventListener {

    
    @EventListener
    public void userRegisterEvent(UserRegisterEvent event) {
        
    }
}

使用注解 @EventListener 使得变成一个事件监听器,在这里我们就能拿到事件中传递的参数 userId,进行我们后续的业务逻辑了

如您在阅读中发现不足,欢迎留言!!!

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/985546.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号