Spring 廣播事件實現

完成功能:
完成廣播功能,即當做一件事情的是,自動觸發廣播,同時告知其他人。
實現思路:
1.定義一個事件類例如MailSendEvent 繼承ApplicationContextEvent
2.定義一個監聽類MailSendListener實現接口ApplicationListener,重寫函數onApplicationEvent用於實現當監聽到事件之後就進行廣播
3.定義實體類MailSender實現接口ApplicationContextAware,獲取上下文,並事件MailSendEvent放入ApplicationContext容器中
5.在Spring XML中配置實體類和監聽類

事件類

package com.event;

import org.springframework.context.ApplicationContext;
import org.springframework.context.event.ApplicationContextEvent;

/**
 * 廣播事件
 * @author Duoduo
 * @version 1.0
 * @date 2017/4/22 10:37
 */
public class MailSendEvent extends ApplicationContextEvent {

    private String sendTo;

    public MailSendEvent(ApplicationContext source, String sendTo) {
        super(source);
        this.sendTo = sendTo;
    }

    public String getSendTo() {
        return sendTo;
    }

    public void setSendTo(String sendTo) {
        this.sendTo = sendTo;
    }
}

監聽廣播類

package com.event;

import org.springframework.context.ApplicationListener;

/**
 * 廣播監聽
 * @author Duoduo
 * @version 1.0
 * @date 2017/4/22 12:05
 */
public class MailSendListener implements ApplicationListener<MailSendEvent> {
    @Override
    public void onApplicationEvent(MailSendEvent mailSendEvent) {
        System.out.println("MailSendListener send to "+mailSendEvent.getSendTo()+" a email");
    }
}

實體類

package com.event;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

/**
 * @author Duoduo
 * @version 1.0
 * @date 2017/4/22 12:09
 */
public class MailSender implements ApplicationContextAware {
    private  ApplicationContext ctx;
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.ctx = applicationContext;
    }

    public  void sendMail(String  sendTo ){
        System.out.println("MailSender send mai ...");

        MailSendEvent mailSendEvent = new MailSendEvent(this.ctx, sendTo);
        ctx.publishEvent(mailSendEvent);
    }
}

Spring XML文件配置

<bean id="MailSendListener" class="com.event.MailSendListener"/>
<bean id="MailSender" class="com.event.MailSender"/>

使用JUnit進行測試

@Test
public void testSetApplicationContext() throws Exception {
    ApplicationContext ctx = new ClassPathXmlApplicationContext("classpath:/spring-another-context.xml");
    MailSender mailSender = (MailSender)ctx.getBean("MailSender");
    mailSender.sendMail("[email protected]");

}

運行結果:當MailSender發送郵件的時候,自動觸發廣播。

MailSender send mai …
MailSendListener send to [email protected] a email

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