Spring---ApplicationContext的事件機制

Spring-ApplicationContext的事件機制

事件源:ApplicationContext。publishEvent()方法:用於主動觸發容器事件。

事件:ApplicationEvent類,容器事件,必須由ApplicationContext發佈。

事件監聽器:ApplicationListener接口,可由容器中任何監聽器Bean擔任。onApplicationEvent(ApplicationEvent event):每當容器內發生任何事件時,此方法都被觸發

容器事件類需繼承ApplicationEvent類,容器事件的監聽器類需實現ApplicationListener接口。

下面給出一個例子(防止看我博客的小白錯誤包的導入 加上了包代碼)

1.首先定義一個EmailEvent類,繼承ApplicationEvent類

import org.springframework.context.ApplicationEvent;

public class EmailEvent extends ApplicationEvent {
    private String address;
    private String text;

    public EmailEvent(Object source) {
        super(source);
    }

    public EmailEvent(Object source, String address, String text) {
        super(source);
        this.address = address;
        this.text = text;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public String getText() {
        return text;
    }

    public void setText(String text) {
        this.text = text;
    }

}

2,定義一個EmailNotifier類,實現ApplicationListener接口,並複寫onApplicationEvent()方法

import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;

public class EmailNotifier implements ApplicationListener {

    @Override
    public void onApplicationEvent(ApplicationEvent event) {
        if (event instanceof EmailEvent) {
            EmailEvent emailEvent = (EmailEvent) event;
            System.out.println("發送郵件的接收地址" + emailEvent.getAddress());
            System.out.println("發送郵件的內容" + emailEvent.getText());
        } else {
            System.out.println("容器內部事件" + event);
        }
    }

}

3.將監聽器配置在Spring容器中(即Spring配置文件中)—-(這裏需要注意容器中所配置的監聽器的類路徑,你的應該和我的不同。不要盲目複製)

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns="http://www.springframework.org/schema/beans"
       xsi:schemaLocation="http://www.springframework.org/schema/beans                  http://www.springframework.org/schema/beans/spring-beans-4.0.xsd">
    <bean class="com.book.spring.EmailNotifier"/>
</beans>

4.編寫主程序main

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class SpringText {

    public static void main(String[] args) {
        ApplicationContext ctx = new ClassPathXmlApplicationContext("/bean.xml");
        EmailEvent ele = new EmailEvent("test", "[email protected]", "this is a test");
        ctx.publishEvent(ele);
    }

}

程序到此結束,運行結果如下:

容器本身的事件:
org.springframework.context.event.ContextRefreshedEvent[source=org.springframework.context.support.ClassPathXmlApplicationContext@b81eda8: startup date [Thu Dec 04 20:20:52 CST 2014]; root of context hierarchy]
發送郵件的接收地址[email protected]
發送郵件的內容this is a test

發佈了22 篇原創文章 · 獲贊 37 · 訪問量 5萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章