实现方式:
spring的事件驱动模型使用的是观察者模式 ,Spring中Observer模式常用的地方是listener的实现。
具体实现:
事件机制的实现需要三个部分,事件源,事件,事件监听器
ApplicationEvent抽象类[事件]
继承自jdk的EventObject,所有的事件都需要继承ApplicationEvent,并且通过构造器参数source得到事件源.
该类的实现类ApplicationContextEvent表示ApplicaitonContext的容器事件.
代码:
public abstract class ApplicationEvent extends EventObject{ private static final long serialVersionUID = 7099057708183571937L; private final long timestamp; public ApplicationEvent(Object source){ super(source); this.timestamp = System.currentTimeMillis(); } public final long getTimestamp(){ return this.timestamp; }}
ApplicationListener接口[事件监听器]
继承自jdk的EventListener,所有的监听器都要实现这个接口。
这个接口只有一个onApplicationEvent()方法,该方法接受一个ApplicationEvent或其子类对象作为参数,在方法体中,可以通过不同对Event类的判断来进行相应的处理。
当事件触发时所有的监听器都会收到消息。
代码:
public interface ApplicationListener extends EventListener{ void onApplicationEvent(E event);}
ApplicationContext接口[事件源]
ApplicationContext是spring中的全局容器,翻译过来是”应用上下文”。
实现了ApplicationEventPublisher接口。
职责:
负责读取bean的配置文档,管理bean的加载,维护bean之间的依赖关系,可以说是负责bean的整个生命周期,再通俗一点就是我们平时所说的IOC容器。
代码:
public interface ApplicationEventPublisher { void publishEvent(ApplicationEvent event);}public void publishEvent(ApplicationEvent event) { Assert.notNull(event, "Event must not be null"); if (logger.isTraceEnabled()) { logger.trace("Publishing event in " + getDisplayName() + ": " + event); } getApplicationEventMulticaster().multicastEvent(event); if (this.parent != null) { this.parent.publishEvent(event); }}
ApplicationEventMulticaster抽象类[事件源中publishEvent方法需要调用其方法getApplicationEventMulticaster]
属于事件广播器,它的作用是把Applicationcontext发布的Event广播给所有的监听器.
代码:
public abstract class AbstractApplicationContext extends DefaultResourceLoaderimplements ConfigurableApplicationContext, DisposableBean{ private ApplicationEventMulticaster applicationEventMulticaster; protected void registerListeners(){ // Register statically specified listeners first.for (ApplicationListener> listener : getApplicationListeners()) {getApplicationEventMulticaster().addApplicationListener(listener);}// Do not initialize FactoryBeans here: We need to leave all regular beans// uninitialized to let post-processors apply to them!String[] listenerBeanNames = getBeanNamesForType(ApplicationListener.class, true, false);for (String lisName : listenerBeanNames) {getApplicationEventMulticaster().addApplicationListenerBean(lisName);}}}
你点的每个“在看”,我都当成了喜欢