关于自定义监听器 onApplicationEvent方法被执行多次的问题

说明

在最近项目开发中,需要在原有项目的基础上需要对原有部分业务数据添加监控功能。所以第一时间想到了使用监听器,事件触发机制解决。没想到在自定义事件和添加监听器功能后,测试代码出现了onApplicationEvent 事件被多次执行的问题。项目是 spring cloud,查阅资料说是由于有多个容器的原因。这里特别记录下解决方式。

1.自定义监听器

1.1 自定义事件


public class WayBillPlanEvent  extends ApplicationEvent {

    private String helloStr ="这是测试 监听器 事件定义内容 ";

    public WayBillPlanEvent(Object source) {
        super(source);
    }


    public String getHelloStr() {
        return helloStr;
    }

    public void setHelloStr(String helloStr) {
        this.helloStr = helloStr;
    }
}

2. 定义监听器

@Component
public class WayBillPlanEventListener{

@Component
public class WayBillPlanEventListener implements ApplicationListener<WayBillPlanEvent> {


    @Async
    public void onApplicationEvent(WayBillPlanEvent wayBillPlanEvent) {
        System.out.println("WayBillPlanEventListener : " + wayBillPlanEvent.getSource().toString() + wayBillPlanEvent.getHelloStr());
    }
}

3.配置监听器

监听器配置有多种方式,这里通过 spring.factories 文件配置,
注意,文件路径为 \resources\META-INF\spring.factories
文件内容:

org.springframework.context.ApplicationListener=\
com.onitor.listeners.WayBillPlanEventListener

4. 发布事件


    @Resource
    private ApplicationContext applicationContext;


	public void listenerNoticeServiceImpl(){
 		WayBillPlanEvent wayBillPlanEvent = new WayBillPlanEvent(this);
        applicationContext.publishEvent(wayBillPlanEvent);

    }

5. 启动项目测试结果

监听器的 onApplicationEvent 方法被执行了多次。
在这里插入图片描述

6. 处理方法

通过注解 @EventListener 可解决 onApplicationEvent 被执行多次的问题。注意通过 @EventListener 注解 需删除 \resources\META-INF\spring.factories 中 ApplicationListener 的配置。

代码


@Component
public class WayBillPlanEventListener{


    @EventListener
    @Async
    public void onApplicationEvent(WayBillPlanEvent wayBillPlanEvent) {
        System.out.println("WayBillPlanEventListener : " + wayBillPlanEvent.getSource().toString() + wayBillPlanEvent.getHelloStr());
    }
}

在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值