java自定义监听器_《Java Spring框架》SpringBoot 自定义监听器(含模拟实现监听管理器)...

前言

在实际工作的过程,我们经常需要监听一个任务实际完成的情况和进度。所以引入监听器的概念。

案例

下面代码都是在Spring Boot 框架下完成

设计一个任务:本任务简单设置:一个循环,每次循环都发布一下进度情况。

importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.context.ApplicationContext;importorg.springframework.stereotype.Component;

@Componentpublic classEventProcess {

@AutowiredprivateApplicationContext applicationContext;public voidprocess(){for(int i = 1; i <= 10; i++){try{/**** 为了演示效果睡眠一秒 ****/Thread.sleep(1000L);

applicationContext.publishEvent(new CustomEvent(this,i));

}catch(InterruptedException e) {

e.printStackTrace();

}

}

}

}

设置一个外部需要关心内容的类

importorg.springframework.context.ApplicationEvent;public class CustomEvent extendsApplicationEvent {private intindex;/*** Create a new {@codeApplicationEvent}.

*

*@paramsource the object on which the event initially occurred or with

* which the event is associated (never {@codenull})*/

public CustomEvent(Object source,intindex) {super(source);this.index =index;

}public intgetIndex() {returnindex;

}

}

再设置一个监听器:重写onApplicationEvent 方法,并且将事件处理成前端可以识别的内容。

importorg.springframework.context.ApplicationListener;importorg.springframework.stereotype.Component;

@Componentpublic class CustomApplicationListener implements ApplicationListener{privateString msg;

@Overridepublic voidonApplicationEvent(CustomEvent event) {

msg= "第"+event.getIndex()+"轮";

System.out.println(msg);

}publicString getMsg() {returnmsg;

}

}

controller 设置请求

importcom.example.event.CustomApp

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值