Spring 广播事件实现

来源:互联网 发布:mac系统没有了 编辑:程序博客网 时间:2024/06/01 07:35

完成功能:
完成广播功能,即当做一件事情的是,自动触发广播,同时告知其他人。
实现思路:
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进行测试

@Testpublic void testSetApplicationContext() throws Exception {    ApplicationContext ctx = new ClassPathXmlApplicationContext("classpath:/spring-another-context.xml");    MailSender mailSender = (MailSender)ctx.getBean("MailSender");    mailSender.sendMail("123@qq.com");}

运行结果:当MailSender发送邮件的时候,自动触发广播。

MailSender send mai …
MailSendListener send to 123@qq.com a email

0 0
原创粉丝点击