JAVA 基于事件和监听实现业务解耦

100 阅读1分钟

本文已参与「新人创作礼」活动,一起开启掘金创作之路。

1. 创建要监听实体类的事件

package com.collmall.system.event;

import com.collmall.system.domain.vo.UserVo;
import lombok.Getter;
import org.springframework.context.ApplicationEvent;

/**
 * 用户监听事件
 * @author 
 * @date 20221026
 */
@Getter
public class UserVoEvent extends ApplicationEvent {

    private UserVo UserVo;

    /**
     * 创建音乐人监听
     * @param source 发生事件的对象
     * @param UserVo  注册监听对象
     */
    public UserVoEvent(Object source, UserVo UserVo) {
        super(source);
        this.UserVo = UserVo;
    }

}


#### 2. 把创建的事件 注册到监听器上

~
package com.collmall.system.listener;

import com.collmall.common.core.exception.base.BaseException;
import com.collmall.system.domain.vo.UserVo;
import com.collmall.system.event.UserVoEvent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

/**
 * 创建一个监听者取完成相应的监听操作 使用@EventListener方法实现注册事件监听
 * @author 
 * @date
 */
@Slf4j
@Component
public class UserVoListener {


    /**
     * 通过@EventListener注解来监听UserVoRegisterEvent事件
     */
    @EventListener
    public void register(UserVoEvent UserVoRegisterEvent) {
        //获取注册用户对象
        UserVo UserVo = UserVoRegisterEvent.getUserVo();
       // 这里处理 业务逻辑 
        // todo  发邮件 ,发短信 等功能

        // 输出用户变更信息
        log.info("用户:"+UserVo.getName()+",状态变更为:"+UserVo.getStatus());
    }
}




#### 3. 发布事件

~
import org.springframework.context.ApplicationContext;

   /**
     * 用户注册方法:所有的事件都要通过applicationContext进行发布
     * @param user
     */
    @Autowired
    private ApplicationContext applicationContext;
    /**
     * 添加 用户
     * @param User
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int addUser (UserVo UserVo) {
       // todo 处理各种业务逻辑
        
        //发布 UserVoRegisterEvent 事件,注册需要监听的UserVo类
        applicationContext.publishEvent(new UserVoEvent(this,UserVo));
        return result;
    }