从Java事件监听到Spring事件监听

从Java事件监听到Spring事件监听

java 事件监听

1. 发布订阅模式

java.util.Observable发布者

public class Observable {
    private boolean changed = false;
    private Vector<Observer> obs;

    /** Construct an Observable with zero Observers. */

    public Observable() {
        obs = new Vector<>();
    }

    /**
     * 为该事件监听器添加事件监听者
     */
    public synchronized void addObserver(Observer o) {
        if (o == null)
            throw new NullPointerException();
        if (!obs.contains(o)) {
            obs.addElement(o);
        }
    }

    /**
     *删除事件监听者
     */
    public synchronized void deleteObserver(Observer o) {
        obs.removeElement(o);
    }

    /**
     * 事件通知
     */
    public void notifyObservers() {
        notifyObservers(null);
    }

    /**
     *有参数的事件通知
     */
    public void notifyObservers(Object arg) {
        /*
         * a temporary array buffer, used as a snapshot of the state of
         * current Observers.
         */
        Object[] arrLocal;

        synchronized (this) {
            /* 
            *只有事件变化时监听者才会工作
             */
            if (!changed)
                return;
            arrLocal = obs.toArray();
            clearChanged();
        }

        for (int i = arrLocal.length-1; i>=0; i--)
            ((Observer)arrLocal[i]).update(this, arg);
    }

    /**
     * 删除所有的监听者
     */
    public synchronized void deleteObservers() {
        obs.removeAllElements();
    }

    /**
     * 事件变化通知方法,由于是protected 修饰所以在实现的过程中我们普遍采用子类继承回调的方式来完成通知操作
     */
    protected synchronized void setChanged() {
        changed = true;
    }

    /**
     * 擦除通知信息
     */
    protected synchronized void clearChanged() {
        changed = false;
    }

    /**
     * 判断事件是否有改变
     */
    public synchronized boolean hasChanged() {
        return changed;
    }

    /**
     * 事件监听者的数目
     */
    public synchronized int countObservers() {
        return obs.size();
    }
}

java.util.Observer订阅者

public interface Observer {
    /**
     *当事件变化时执行该方法
     */
    void update(Observable o, Object arg);
}

2.事件/监听模式

java.util.EventObject事件对象

public class EventObject implements java.io.Serializable {

    private static final long serialVersionUID = 5516075349620653480L;

    /**
     * 事件源
     */
    protected transient Object  source;

    /**
     * 构造器初始化
     */
    public EventObject(Object source) {
        if (source == null)
            throw new IllegalArgumentException("null source");

        this.source = source;
    }

    /**
     *事件到达时,获取Source
     */
    public Object getSource() {
        return source;
    }

    /**
     * 返回当前的事件对象
     */
    public String toString() {
        return getClass().getName() + "[source=" + source + "]";
    }
}

事件对象总是关联着事件源

java.util.EventListener事件监听接口(标记接口)

public interface EventListener {
}

该接口主要是作为标记接口,在Spring Spring Cloud中均有相应的实现:
在这里插入图片描述

Spring 事件/监听

org.springframework.context.ApplicationEvent

org.springframework.context.ApplicationListener

org.springframework.boot.context.config.ConfigFileApplicationListener管理配置文件如:application.properties application.yaml

java SPI

java.util.ServiceLoader

Spring SPI:

# Application Listeners
org.springframework.context.ApplicationListener=\
org.springframework.boot.ClearCachesApplicationListener,\
org.springframework.boot.builder.ParentContextCloserApplicationListener,\
org.springframework.boot.context.FileEncodingApplicationListener,\
org.springframework.boot.context.config.AnsiOutputApplicationListener,\
org.springframework.boot.context.config.ConfigFileApplicationListener,\
org.springframework.boot.context.config.DelegatingApplicationListener,\
org.springframework.boot.context.logging.ClasspathLoggingApplicationListener,\
org.springframework.boot.context.logging.LoggingApplicationListener,\
org.springframework.boot.liquibase.LiquibaseServiceLocatorApplicationListener

3.Spring监听模式

@FunctionalInterface
public interface ApplicationListener<E extends ApplicationEvent> extends EventListener {

	/**
	 * 处理一个应用事件
	 * @param event the event to respond to
	 */
	void onApplicationEvent(E event);

}

如何控制顺序:
实现Ordered以及标记Order

在Spring中,数值越小越优先

猜你喜欢

转载自blog.csdn.net/shang_xs/article/details/86560994