JAVA 基于事件和监听实现业务解耦
1. 创建要监听实体类的事件
package com.collmall.system.event;
import com.collmall.system.domain.vo.UserVo;
import lombok.Getter;
import org.springframework.context.ApplicationEvent;
@Getter
public class UserVoEvent extends ApplicationEvent {
private UserVo 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;
@Slf4j
@Component
public class UserVoListener {
@EventListener
public void register(UserVoEvent UserVoRegisterEvent) {
UserVo UserVo = UserVoRegisterEvent.getUserVo();
log.info("用户:"+UserVo.getName()+",状态变更为:"+UserVo.getStatus());
}
}
3. 发布事件
import org.springframework.context.ApplicationContext;
@Autowired
private ApplicationContext applicationContext;
@Override
@Transactional(rollbackFor = Exception.class)
public int addUser (UserVo UserVo) {
applicationContext.publishEvent(new UserVoEvent (this,UserVo));
return result;
}