事件监听
- 事件监听通常包含事件Event、监听者或则订阅者Listener和事件发布者Publisher。
- Publisher发布Event触发Listener,然后Listener执行相关操作。
事件的核心类EventObject和EventListener
- 事件是通过java.util.EventObject封装的,EventObject中的resource是封装的事件源,resource可以是事件发布者或则其他任何对象
- 监听是通过EventListener接口标记的,所有监听者都要实现该接口。
Spring事件监听模式就是ApplcationEvent和ApplicationListener<T extent ApplicationEvent>,然后通过ApplicationContext的publishEvent方法发布事件的。其中ApplicationEvent和ApplicationListener分别继承了EventObject和EventListener。
Spring事件监听模式示例代码:
//自定义事件
public class SoldOutEvent extends ApplicationEvent {
public SoldOutEvent(Object source) {
super(source);
}
@Override
public String toString() {
return "This is sold out.";
}
}
//自定义监听者
@Component
public class SoldOutEventListener implements ApplicationListener<SoldOutEvent>, ApplicationContextAware {
private ApplicationContext context;
@Override
public void onApplicationEvent(SoldOutEvent event) {
//事件源通常是Publisher Publisher在发布的事件的时候把自己this当成事件源传输,事件源可以是任意一个普通对象
System.out.println("SoldOutEvent事件触发,接收到事件源Source:" + event.getSource());
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
context = applicationContext;
}
}
//事件发布
@Component
public class EventPublisher implements ApplicationContextAware {
private ApplicationContext context;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
context = applicationContext;
}
public void publish() {
if (context == null) {
throw new RuntimeException("Application context is not init!");
}
context.publishEvent(new SoldOutEvent(this));
}
}
Application发布事件广播的核心: