當前位置:
首頁 >
前端技术
> javascript
>内容正文
javascript
Spring中的事件机制
生活随笔
收集整理的這篇文章主要介紹了
Spring中的事件机制
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
Spring的事件驅動模型由三部分組成:
- 事件(消息):ApplicationEvent,繼承自JDK的EventObject,所有事件將繼承它,并通過source得到事件源。
- 事件發布者(生產者):ApplicationEventPublisher(一般用這個)及ApplicationEventMulticaster接口,使用這個接口,我們的Service就擁有了發布事件的能力。
- 事件訂閱者(消費者):ApplicationListener,繼承自JDK的EventListener,所有監聽器將繼承它。
下面寫一個小例子:
1.事件(消息)? ? 繼承自ApplicationEvent
import org.springframework.context.ApplicationEvent;/*** 類似于 Message* 相當于-Rabbitmq的message-一串二進制數據流* */ 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.事件發布者(生產者)? 使用ApplicationEventPublisher接口
?
@RequestMapping(value = "/push",method = RequestMethod.GET)public BaseResponse pushOrder(){try {//根據上面消息類,新建一個消息PushOrderRecordEvent event=new PushOrderRecordEvent(this,"orderNo_20180821001","物流12");//使用ApplicationEventPublisher這個接口把消息發送出去publisher.publishEvent(event);}catch (Exception e){log.error("異常:");}return response;}3.?事件訂閱者(消費者):實現ApplicationListener
泛型為事件(消息)?:PushOrderRecordEvent
小知識:@component (把普通pojo實例化到spring容器中,相當于配置文件中的<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("監聽到的記錄是: {} ",event);} }?
總結
以上是生活随笔為你收集整理的Spring中的事件机制的全部內容,希望文章能夠幫你解決所遇到的問題。