spring事件-Event

直接上代码

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

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值