先写个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);
}
}