spring事件派发

先写个Event类

就是派发的事件用来封装消息 继承 ApplicationEvent 

package net.okdi.o2o.event;

import org.springframework.context.ApplicationEvent;
import org.springframework.stereotype.Component;
@SuppressWarnings("serial")
@Component
public class Event extends ApplicationEvent{
	
    private String eventMsg ;
    
	public Event(Object source) {
		super(source);
	}
	public String getEventMsg() {
		return eventMsg;
	}
	public void setEventMsg(String eventMsg) {
		this.eventMsg = eventMsg;
	}
	
}

在写个派发事件的监听类 就像是定时任务触发的业务处理类 只是触发条件不同   

实现ApplicationListener就行了

package net.okdi.o2o.event;

import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;
@SuppressWarnings("rawtypes")
@Component
public class EventListener implements ApplicationListener  {

	@Override
	public void onApplicationEvent(ApplicationEvent event) {
		//监听到事件后要干什么
      		if (event instanceof Event) {
      			Event newEvent = (Event) event;
				System.out.println("监听到事件派发"+newEvent.getEventMsg());
			}
	}

}

再写个类用来派发事件

实现ApplicationEventPublisherAware

实现后会要求重写setApplicationEventPublisher 这个方法 其实就是用来为你写的这个类里面注入一个pusher的 然后就用这个pusher发布任务就行了

package net.okdi.o2o.event;

import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.ApplicationEventPublisherAware;
import org.springframework.stereotype.Component;
@Component
public class EventPusher implements ApplicationEventPublisherAware {
    private ApplicationEventPublisher applicationEventPublisher;
	
	@Override
	public void setApplicationEventPublisher(ApplicationEventPublisher pusher) {
		applicationEventPublisher = pusher;
	}
    
	public void pushEvent(){
		System.out.println("发布执行");
		Event event = new Event(this);
		event.setEventMsg("zmn测试事件发布");
		applicationEventPublisher.publishEvent(event);
	}

}



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值