Spring - 设计模式 - 发布订阅模式

目录

1.Spring的发布订阅模式组成

1.1场景说明

1.2创建UserUpdateEvent 事件

1.3创建监听类

1.4发布UserUpdateEvent 事件


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;
    }
}


 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值