如何使用SmartApplicationListener有顺序的监听同一个事件Event

本文介绍了如何在SpringBoot中实现有序的事件监听器,通过重写supportsEventType、supportsSourceType方法和getOrder方法来控制事件监听顺序。以用户注册发送邮件为例,展示了如何创建事件和监听器,并通过设置不同的getOrder值来调整监听顺序。同时,文章还探讨了使用@Async进行异步监听的情况,以及任务线程池的配置,说明了同步和异步监听并存时执行顺序的特点。
摘要由CSDN通过智能技术生成

SpringBoot 有序事件监听器

java

实现SmartApplicationListener 重写supportsEventType、supportsSourceType来区分是否是我们监听的事件,只有两个方法同时返回true时才会执行,getOrder这个方法可以解决执行监听的顺序问题,return的数值越小证明优先级越高,执行顺序越靠前。

用户注册发送邮件

首先创建一个事件,监听都是围绕着事件

import com.base.client.model.vo.UserVO;
import lombok.Getter;
import org.springframework.context.ApplicationEvent;

/**
 * 用户创建事件
 *
 * @author arjun
 * @date 2020/12/09
 */
@Getter
public class UserRegisterEvent extends ApplicationEvent {
   
    /**
     * 发送的内容
     */
    private UserVO content;

    /**
     * 重写构造器
     *
     * @param source  发送事件的对象
     * @param content 发送的内容
     */
    public UserRegisterEvent(Object source, UserVO content) {
   
        super(source);
        this.content = content;
    }
}

创建UserService只用于实现注册事件发布功能(当然业务逻辑也是可以写,这里只为测试)

这里注入 ApplicationEventPublisher接口

import com.base.client.model.vo.UserVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Service;

/**
 * @author arjun
 * @date 2020/12/09
 */
@Service
public class UserService {
   

    @Autowired
    private ApplicationEventPublisher eventPublisher;

    public void register(UserVO vo) {
   
        System.out.println("----------------发布注册事件----------------------");
        // 发布 UserRegisterEvent 事件
        eventPublisher.publishEvent(new UserRegisterEvent(this, vo));
    }
}

ApplicationEvent监听所有事件发布,SmartApplicationListener接口添加了两个方法supportsEventTypesupportsSourceType来区分是否是我们监听的事件,只有两个方法同时返回true时才会执行onApplicationEventgetOrder这个方法可以解决执行监听的顺序问题,return的数值越小证明优先级越高,执行顺序越靠前。

import com.base.client.model.vo.UserVO;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.event.SmartApplicationListener;
import org.springframework.stereotype.Component;

/**
 * @author arjun
 * @date 2020/12/09
 */
@Component
public class UserRegisterListener implements SmartApplicationListener {
   
    @Override
    public boolean supportsEventType(Class<? extends ApplicationEvent> aClass) {
   
        return aClass == UserRegisterEvent.class;
    }

    @Override
    public boolean supportsSourceType(Class<?
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值