事件的发布监听机制类似于观察者模式,利用事件的监听机制可以实现业务的发起与业务的处理解耦,更能体现单一职责原则,例如:新用户注册,我们需要发送邮件通知用户,触发了注册事件,监听者就能监听到注册事件,进行后续操作,事件发布与监听一般需要三步:
- 1、定义事件
- 2、发布事件
- 3、监听事件
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,进行我们后续的业务逻辑了
如您在阅读中发现不足,欢迎留言!!!



