Spring监听事件使用了设计模式中的观察者模式。
定义监听事件
自定义Event类,继承自ApplicationEvent
。此处我定义了一个SceneChangeEvent
:
import org.springframework.context.ApplicationEvent;
/**
* @author windmyf
*/
public class SceneChangeEvent extends ApplicationEvent {
private String sceneName;
private String sceneDesc;
public String getSceneName() {
return sceneName;
}
public void setSceneName(String sceneName) {
this.sceneName = sceneName;
}
public String getSceneDesc() {
return sceneDesc;
}
public void setSceneDesc(String sceneDesc) {
this.sceneDesc = sceneDesc;
}
/**
* Create a new {@code ApplicationEvent}.
*
* @param source the object on which the event initially occurred or with
* which the event is associated (never {@code null})
*/
public SceneChangeEvent(Object source) {
super(source);
}
}
定义监听器
定义一个监听器,实现ApplicationListener
接口,重写onApplicationEvent()
方法
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;
/**
* @author windmyf
*/
@Component
public class SceneChangeListener implements ApplicationListener<SceneChangeEvent> {
@Override
public void onApplicationEvent(SceneChangeEvent event) {
// TODO 监听逻辑处理
System.out.println("场景发生了改变,场景为:" + event.getSceneDesc());
}
}
Push事件类
该类实现ApplicationContextAware
接口,通过setApplicationContext(ApplicationContext applicationContext)
方法获取上下文,自定义事件push方法,并在逻辑中调用applicationContext.publishEvent();
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
/**
* @author windmyf
*/
@Component
public class EventPushService implements ApplicationContextAware {
private ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
public void pushEvent(SceneChangeEvent sceneChangeEvent){
// TODO 其他逻辑处理
System.out.println("发送场景改变消息:【" + sceneChangeEvent.getSceneName() + ","
+ sceneChangeEvent.getSceneDesc()+"】");
// 转发事件
applicationContext.publishEvent(sceneChangeEvent);
}
}
当产生SceneChangeEvent
事件的时候,会默认使用SceneChangeListener
中的onApplicationEvent
方法来进行监听器的处理。