Spring发布监听机制

一、源码

   (1)、ApplicationEvent抽象类

public abstract class ApplicationEvent extends EventObject {

    /** use serialVersionUID from Spring 1.2 for interoperability */
    private static final long serialVersionUID = 7099057708183571937L;

    /** System time when the event happened */
    private final long timestamp;
    /**
     * 创建一个新的ApplicationEvent.*/
    public ApplicationEvent(Object source) {
        super(source);
        this.timestamp = System.currentTimeMillis();
    }
    /**
     * 获取事件产生的时间
     */
    public final long getTimestamp() {
        return this.timestamp;
    }
}

   (2)、ApplicationListener接口--监听容器中发布的事件。

public interface ApplicationListener<E extends ApplicationEvent> extends EventListener {

    /**
     * Handle an application event.*/
    void onApplicationEvent(E event);

}

   (3)、ApplicationEventPublisher接口

public interface ApplicationEventPublisher {

    /**
     * 会通知所有注册该事件的监听器,这些监听可能是spring框架的监听器,也有可能是特定的监听器。*/
    void publishEvent(ApplicationEvent event);

    /**
     * Notify all <strong>matching</strong> listeners registered with this
     * application of an event.*/
    void publishEvent(Object event);

}

二、使用例子实战

 (1)、创建一个类,作为传递的事件内容

      

public class Person {
    private int age;
    private String name;
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
}

  (2)、创建一个ApplicationEvent接口的实现类

@Component
public class Event extends ApplicationEvent {
    public Event(Person source) {
        super(source);
    }
}

(3)、创建ApplicationListener接口实现类,监听器的实现

@Component
public class MyListener implements ApplicationListener<Event> {
    @Override
    public void onApplicationEvent(Event event) {
        Person person = (Person) event.getSource();
        System.out.println(person.getAge()); //获取到发布的事件
        System.out.println(event.getTimestamp()); //获取到事件发布的时间
    }
}

  (4)、创建Configuration配置类

@Configuration
@ComponentScan("com.spring.event")
public class EventConfiguration {
    @Bean
    public Person person(){
        Person person = new Person();
        person.setName("haha");
        person.setAge(10);
        return person;
    }

}

(5)、启动容器,并在容器中进行事件发布

public class Test {
    public static void main(String[] args) {

        ApplicationContext applicationContext = new AnnotationConfigApplicationContext(EventConfiguration.class);
        applicationContext.publishEvent(new Event((Person) applicationContext.getBean("person")));
    }
}

(6)、可以获取到监听结果

10
1578452283603
原文地址:https://www.cnblogs.com/mayang2465/p/12165379.html