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万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章