Spirng中的事件机制

来源:互联网 发布:大乐透,简单公式算法 编辑:程序博客网 时间:2024/05/21 19:30

在debug spring源码的时候,发现spring有一套事件机制,其实在以前debug tomcat源码的时候也发现有一套事件机制,学习之后估计两者的原理大致都是一样的,都是根据java.util.EventObject和java.util.EventListener这两个类或接口实现的。

spring相关实现

  • ApplicationEvent,spring中的事件抽象类,继承自java.util.EventObject,简单了解了一下源码后,发现spring有4种事件,分别是ContextClosedEvent、ContextRefreshedEvent、ContextStartedEvent、ContextStoppedEvent。
  • ApplicationListener,spring中的事件监听者,继承自java.util.EventListener这个接口。ApplicationListener中有一个onApplicationEvent方法,这个方法是用来处理相关事件的。
  • ApplicationEventMulticaster,这个类是spring中的广播类,可以把新的事件广播到所有的监听者,并处理相关事件。
  • ApplicationEventPublisher,事件发布接口,当有新事件的时候,发布新事件,调用广播类去广播这个事件。

当spring中有一个新的事件产生的时候,会去发布这个事件,然后让广播去广播这个事件,让其他所有的监听者都能知道新事件的产生。例如:在使用

ApplicationContext ac = new ClassPathXmlApplicationContext("classpath:spring.xml");

ClassPathXmlApplicationContext加载spring配置文件的时候,会产生一个ContextRefreshedEvent事件,当加载配置文件完成的时候,spring会把加载完成配置文件这个事件广播给spring中所有的上下文。

代码示例

这里我简单的根据java.util.EventObject和java.util.EventListener这两个类或接口写了一个demo:

事件父类:

public class SimpleEvent extends EventObject{    /**     * Constructs a prototypical Event.     *     * @param source The object on which the Event initially occurred.     * @throws IllegalArgumentException if source is null.     */    public SimpleEvent(Object source) {        super(source);    }}

发送邮件事件:

public class EmailEvent extends SimpleEvent {    private Object obj;    private String email;    private String context;    /**     * Constructs a prototypical Event.     *     * @param source The object on which the Event initially occurred.     * @throws IllegalArgumentException if source is null.     */    public EmailEvent(Object source) {        super(source);    }    /**     * Instantiates a new Email event.     *     * @param source  the source     * @param email   the email     * @param context the context     */    public EmailEvent(Object source, String email, String context) {        super(source);        this.obj = source;        this.email = email;        this.context = context;    }    /**     * Gets obj.     *     * @return the obj     */    public Object getObj() {        return obj;    }    /**     * Sets obj.     *     * @param obj the obj     */    public void setObj(Object obj) {        this.obj = obj;    }    /**     * Gets email.     *     * @return the email     */    public String getEmail() {        return email;    }    /**     * Sets email.     *     * @param email the email     */    public void setEmail(String email) {        this.email = email;    }    /**     * Gets context.     *     * @return the context     */    public String getContext() {        return context;    }    /**     * Sets context.     *     * @param context the context     */    public void setContext(String context) {        this.context = context;    }}

发送短信事件:

public class SMSEvent extends SimpleEvent {    private Object obj;    private String phoneNumber;    private String context;    /**     * Constructs a prototypical Event.     *     * @param source The object on which the Event initially occurred.     * @throws IllegalArgumentException if source is null.     */    public SMSEvent(Object source) {        super(source);    }    /**     * Instantiates a new Sms event.     *     * @param source      the source     * @param phoneNumber the phone number     * @param context     the context     */    public SMSEvent(Object source, String phoneNumber, String context) {        super(source);        this.obj = source;        this.phoneNumber = phoneNumber;        this.context = context;    }    /**     * Gets phone number.     *     * @return the phone number     */    public String getPhoneNumber() {        return phoneNumber;    }    /**     * Sets phone number.     *     * @param phoneNumber the phone number     */    public void setPhoneNumber(String phoneNumber) {        this.phoneNumber = phoneNumber;    }    /**     * Gets context.     *     * @return the context     */    public String getContext() {        return context;    }    /**     * Sets context.     *     * @param context the context     */    public void setContext(String context) {        this.context = context;    }    /**     * Gets obj.     *     * @return the obj     */    public Object getObj() {        return obj;    }    /**     * Sets obj.     *     * @param obj the obj     */    public void setObj(Object obj) {        this.obj = obj;    }}

监听器接口:

public interface Listener extends EventListener {    void handle(SimpleEvent event);}

监听器实现类

public class SimpleListener implements Listener {    @Override    public void handle(SimpleEvent event) {        if(event instanceof EmailEvent){            sendMail((EmailEvent) event);        } else if(event instanceof SMSEvent){            sendSMS((SMSEvent) event);        }    }    private void sendSMS(SMSEvent event) {        System.out.println("发送短信开始");        System.out.println("发件人:" + event.getObj());        System.out.println("收件人:" + event.getPhoneNumber());        System.out.println("短信内容:" + event.getContext());    }    private void sendMail(EmailEvent event) {        System.out.println("发送邮件开始");        System.out.println("发件人:" + event.getObj());        System.out.println("收件人:" + event.getEmail());        System.out.println("邮件内容:" + event.getContext());    }}

广播接口

public interface Multicaster {    void addListener(Listener listener);    void removeListener(Listener listener);    void multicastEvent(SimpleEvent... event);}

广播实现类:

public class SimpleMulticaster implements Multicaster {    private Vector<Listener> vector = new Vector<Listener>();    @Override    public void addListener(Listener listener) {        vector.add(listener);    }    @Override    public void removeListener(Listener listener) {        vector.remove(listener);    }    @Override    public void multicastEvent(SimpleEvent... event) {        for (Listener listener : vector) {            for (SimpleEvent e : event)                listener.handle(e);        }    }}

测试类:

public class Main {    public static void main(String[] args) {        Multicaster simpleMuticaster = new SimpleMulticaster();        Listener simpleListener = new SimpleListener();        simpleMuticaster.addListener(simpleListener);        simpleMuticaster.multicastEvent(new SimpleEvent[]{new EmailEvent("zhangsan", "lisi", "hello,lisi!"), new SMSEvent("zhangsan", "13888888888", "hello,lisi!")});    }}
0 0
原创粉丝点击