直接上代码
1.定义事件类
package com.zhm.root.event;
import com.zhm.root.mbg.model.UmsAdmin;
import org.springframework.context.ApplicationEvent;
import java.util.List;
// 定义一个事件传递的中间对象
public class EmployeeEvent extends ApplicationEvent {
// 可以自定义事件传递的参数
private UmsAdmin currentAdmin;
private List<Integer> insertEmployeeList;
private List<Integer> updateEmployeeList;
public EmployeeEvent(Object source,UmsAdmin currentAdmin, List<Integer> insertEmployeeList,List<Integer> updateEmployeeList) {
super(source);
this.currentAdmin = currentAdmin;
this.insertEmployeeList = insertEmployeeList;
this.updateEmployeeList = updateEmployeeList;
}
public List<Integer> getInsertEmployeeList() {
return insertEmployeeList;
}
public void setInsertEmployeeList(List<Integer> insertEmployeeList) {
this.insertEmployeeList = insertEmployeeList;
}
public List<Integer> getUpdateEmployeeList() {
return updateEmployeeList;
}
public void setUpdateEmployeeList(List<Integer> updateEmployeeList) {
this.updateEmployeeList = updateEmployeeList;
}
public UmsAdmin getCurrentAdmin() {
return currentAdmin;
}
public void setCurrentAdmin(UmsAdmin currentAdmin) {
this.currentAdmin = currentAdmin;
}
}
2.在需要地方发布事件
EmployeeEvent event = new EmployeeEvent(this,currentAdmin,insertEmployee,new ArrayList<>());
applicationContext.publishEvent(event);
3.对应的地方监听事件
@EventListener
public void employeeUpdateEvent(EmployeeEvent employeeEvent){
LOGGER.info("收到事件消息,开始维护数据");
}
有个注意点:当发布事件时在一个事物中,也就是用@Transactional包含,则事件监听的方法也是受该事物影响。所以如果不需要保证监听的方法也需要被事物控制,可以选择使用@TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT) 注解替代
事物相关参考:https://www.jdon.com/50746