Spring Event

Spring Event 是基于观察者模式实现,介绍其以前,咱们先介绍下JDK提供的观察者模型数据结构

观察者:Observer,多线程

 

被观察:Observableapp

 

 

当被观察者改变时,其须要通知全部关联的观察者。Observable实现逻辑以下:ide

一、 Observable定义了一个数据结构:Vector<Observer>,记录关联的Observer。
二、 通知关联的观察者:调用方法notifyObservers(调用全部Observer的update方法)。

 

好了,下面咱们介绍Spring基于观察者模式的Event机制this

首先介绍Spring Event的关键的类spa

一、 ApplicationEvent 事件线程

二、 ApplicationListener 监听(Observer)code

三、 ApplicationEventPublisher 发布(Observable)server

 

总体逻辑以下:blog

ApplicationEventPublisher发布ApplicationEvent给关联的ApplicationListener。

 

根据观察者模式,咱们能够推导出来:

       ApplicationEventPublisher持有关联的ApplicationListener列表,调用ApplicationListener的方法(将ApplicationEvent做为入参传入过去),达到通知的效果。但问题来了,ApplicationEventPublisher如何知道这个ApplicationListener发给哪一个ApplicationListener呢?

下面咱们一步一步解析。

ApplicationListener(Observer)

 

ApplicationEventPublisher(Observable)

正在实现ApplicationEventPublisher.publishEvent这个方法的有两个类

有两个类AbstractApplicationContext和它的子类SimpleApplicationEventMulticaster

 

AbstractApplicationContext功能是存放全部关联的ApplicationListener。数据结构以下:

Map<ListenerCacheKey, ListenerRetriever> retrieverCache。

ListenerCacheKey构成:

一、ResolvableType eventType(对应的是ApplicationEvent)

二、Class<?> sourceType(对应的是EventObject)

ListenerRetriever构成:

一、 Set<ApplicationListener<?>> applicationListeners(监听)

答案很显然,ApplicationEventPublisher是经过ApplicationEvent(继承ApplicationEvent的Class类)类型来关联须要调用的ApplicationListener。

 SimpleApplicationEventMulticaster的功能是:多线程调用全部关联的ApplicationListener的onApplicationEvent方法的。

实践:

建立Event

public class Event extends ApplicationEvent {
    private String message;
    public Event(Object source, String message) {
        super(source);
        this.message = message;
    }
    public String getMessage() {
        return message;
    }
}

建立监听:

一、实现ApplicationListener
@Component
public class ImplementsListener implements ApplicationListener<Event> {
    @Override
    public void onApplicationEvent(Event event) {
        //TODO
    }
}
二、加@EventListener注解
@Component
public class AnnotationListener {
    @EventListener
    public void eventListener(Event event) {
        //TODO
    }
}

事件发布:

@Component
public class EventPublisher {
    @Autowired
    private ApplicationEventPublisher applicationEventPublisher;
    public void publish() {
        applicationEventPublisher.publishEvent(new Event(this, "it's demo"));
    }
}

自定义事件广播:

@Component(APPLICATION_EVENT_MULTICASTER_BEAN_NAME)
public class CustomApplicationEventMulticaster extends AbstractApplicationEventMulticaster {
    @Override public void multicastEvent(ApplicationEvent event) {
        //TODO custom invokeListener(listener, event);
    }
    @Override public void multicastEvent(ApplicationEvent event, ResolvableType eventType) {
        //TODO custom invokeListener(listener, event);
    }
}
相关文章
相关标签/搜索