當(dāng)前位置:
首頁 >
前端技术
> javascript
>内容正文
javascript
Spring中的事件机制
生活随笔
收集整理的這篇文章主要介紹了
Spring中的事件机制
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
Spring的事件驅(qū)動(dòng)模型由三部分組成:
- 事件(消息):ApplicationEvent,繼承自JDK的EventObject,所有事件將繼承它,并通過source得到事件源。
- 事件發(fā)布者(生產(chǎn)者):ApplicationEventPublisher(一般用這個(gè))及ApplicationEventMulticaster接口,使用這個(gè)接口,我們的Service就擁有了發(fā)布事件的能力。
- 事件訂閱者(消費(fèi)者):ApplicationListener,繼承自JDK的EventListener,所有監(jiān)聽器將繼承它。
下面寫一個(gè)小例子:
1.事件(消息)? ? 繼承自ApplicationEvent
import org.springframework.context.ApplicationEvent;/*** 類似于 Message* 相當(dāng)于-Rabbitmq的message-一串二進(jìn)制數(shù)據(jù)流* */ public class PushOrderRecordEvent extends ApplicationEvent{private String orderNo;private String orderType;public PushOrderRecordEvent(Object source, String orderNo, String orderType) {super(source);this.orderNo = orderNo;this.orderType = orderType;}public String getOrderNo() {return orderNo;}public void setOrderNo(String orderNo) {this.orderNo = orderNo;}public String getOrderType() {return orderType;}public void setOrderType(String orderType) {this.orderType = orderType;}@Overridepublic String toString() {return "PushOrderRecordEvent{" +"orderNo='" + orderNo + '\'' +", orderType='" + orderType + '\'' +'}';} }?
?2.事件發(fā)布者(生產(chǎn)者)? 使用ApplicationEventPublisher接口
?
@RequestMapping(value = "/push",method = RequestMethod.GET)public BaseResponse pushOrder(){try {//根據(jù)上面消息類,新建一個(gè)消息PushOrderRecordEvent event=new PushOrderRecordEvent(this,"orderNo_20180821001","物流12");//使用ApplicationEventPublisher這個(gè)接口把消息發(fā)送出去publisher.publishEvent(event);}catch (Exception e){log.error("異常:");}return response;}3.?事件訂閱者(消費(fèi)者):實(shí)現(xiàn)ApplicationListener
泛型為事件(消息)?:PushOrderRecordEvent
小知識(shí):@component (把普通pojo實(shí)例化到spring容器中,相當(dāng)于配置文件中的<bean id="" class=""/>)
@Component public class PushOrderRecordListener implements ApplicationListener<PushOrderRecordEvent>{private static final Logger log= LoggerFactory.getLogger(PushOrderRecordListener.class);@Autowiredprivate OrderRecordMapper orderRecordMapper;@Overridepublic void onApplicationEvent(PushOrderRecordEvent event) {log.info("監(jiān)聽到的記錄是: {} ",event);} }?
總結(jié)
以上是生活随笔為你收集整理的Spring中的事件机制的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 物候现象是什么
- 下一篇: Springboot-data-jpa