目录
1.Spring的发布订阅模式组成
1.1事件对象(extends ApplicationEvent)
1.2监听类(Implements ApplicationEventListener)
1.3发布通道 ApplicationEventPublisher (通过implements ApplicationEventPublisherAware 获取)
1.1场景说明
Service业务层修改User 对象,对User对象进行持久化的时候,发布UserUpdateEvent 事件,监听到这个事件,通过邮件方式,通知用户!
1.2创建UserUpdateEvent 事件
/**
* @version V1.0
* @Author: yang
* @Company 纵横格子
* @Description 事件类 User修改的时候创建这个事件,需要集成ApplicationEvent 表示这个是一个Spring的事件
* @Date: 2022/7/28 11:33
*/
@Component
public class UserUpdateEvent extends ApplicationEvent {
private final User user;
public UserUpdateEvent(Object source, User user) {
super(source);
this.user = user;
}
public User getUser() {
return user;
}
}
1.3创建监听类
/**
* @version V1.0
* @Author: yang
* @Company 纵横格子
* @Description 监听时间类 实现ApplicationListener接口 指定泛型为监听的自定义事件对象
* 重写onApplicationEvent 方法,做监听到事件后的操作,这是是通知用户
* @Date: 2022/7/28 11:46
*/
@Component
public class SpringEventListener implements ApplicationListener<UserUpdateEvent> {
@Override
public void onApplicationEvent(UserUpdateEvent event) {
// 监听到事件发布了
System.out.println("修改后的对象为: = [ "+event.getUser()+" ]");
// 发送邮件通知用户
}
}
1.4发布UserUpdateEvent 事件
/**
* @version V1.0
* @Author: yang
* @Company 纵横格子
* @Description 用户User对象业务成,此处修改的user对象,需要发布UserUpdateEvent 事件
* 发布事件需要实现 ApplicationEventPublisherAware 接口,拿到ApplicationEventPublisher 对象,用该对象发布事件消息
* @Date: 2022/7/28 11:38
*/
@Component
public class UserUpdateService implements ApplicationEventPublisherAware {
private ApplicationEventPublisher applicationEventPublisher = null;
public void updateUser(){
User user = new User();
user.setName("该名称");
// 1.调用持久层保存用户
// 2.操作了用户的修改,此处需要发布UserUpdateEvent事件,用于发送邮件提醒用户信息变更了
if(applicationEventPublisher == null){
// 报错 获取不到Spring发布事件对象
System.out.println("获取不到事件发布对象 ApplicationEventPublisher ");
}
// 此处发布事件,发布的时间对象为 UserUpdateEvent
applicationEventPublisher.publishEvent(new UserUpdateEvent(this,user));
}
/**
*
* @param applicationEventPublisher
*/
@Override
public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
this.applicationEventPublisher = applicationEventPublisher;
}
}