Spring發佈監聽機制

1、源碼spring

   (1)、ApplicationEvent抽象類app

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接口ide

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);

}

2、使用例子實戰this

 (1)、建立一個類,做爲傳遞的事件內容spa

      

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接口的實現類code

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

(3)、建立ApplicationListener接口實現類,監聽器的實現blog

@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
相關文章
相關標籤/搜索