前言
在实际工作的过程,我们经常需要监听一个任务实际完成的情况和进度。所以引入监听器的概念。
案例
下面代码都是在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