博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
精通SpringBoot——第四篇:Spring事件 Application Event
阅读量:7222 次
发布时间:2019-06-29

本文共 1909 字,大约阅读时间需要 6 分钟。

Spring的事件为Bean与Bean之间的通信提供了支持,当我们系统中某个Spring管理的Bean处理完某件事后,希望让其他Bean收到通知并作出相应的处理,这时可以让其他Bean监听当前这个Bean所发送的事件。

要实现事件的监听,我们要做两件事:

1:自定义事件,继承ApplicationEvent接口
2:定义事件监听器,实现ApplicationListener
3:事件发布类

/** * @TODO // 自定义事件,继承ApplicationEvent接口 * @Author Lensen * @Date 2018/7/22 * @Description */public class SendMsgEvent extends ApplicationEvent {    private static final long serialVersionID = 1L;    // 收件人    public String receiver;    // 收件内容    public String content;    public SendMsgEvent(Object source) {        super(source);    }    public SendMsgEvent(Object source, String receiver, String content) {        super(source);        this.receiver = receiver;        this.content = content;    }    public void output(){        System.out.println("I had been sand a msg to " + this.receiver);    }}
/** * @TODO //定义事件监听器,实现ApplicationListener * @Author Lensen * @Date 2018/7/22 * @Description */@Componentpublic class MsgListener implements ApplicationListener
{ @Override public void onApplicationEvent(SendMsgEvent sendMsgEvent) { sendMsgEvent.output(); System.out.println(sendMsgEvent.receiver + "received msg : " + sendMsgEvent.content ); }}

事件发布类

@Componentpublic class Publisher {    @Autowired    ApplicationContext applicationContext;    public void publish(Object source, String receiver, String content){        applicationContext.publishEvent(new SendMsgEvent(source, receiver, content));    }}

测试消息:WebConfig.class主要是为了扫描Publisher 和Listener类。里面有两个注解@ComponenScan和@Configuration。

public static void main(String[] args) {        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(WebConfig.class);        Publisher publisher = applicationContext.getBean(Publisher.class);        publisher.publish("Hello,World!","Mr.Lensen", "I Love U");    }

结果:

I had been sand a msg to Mr.LensenMr.Lensen received msg : I Love U

转载地址:http://lmhym.baihongyu.com/

你可能感兴趣的文章
根据第三方库spire.pdf使用指定打印机打印pdf文件
查看>>
mysql之存储过程
查看>>
使用intelliJ创建 spring boot + gradle + mybatis站点
查看>>
第八章 方法
查看>>
maven中常用命令
查看>>
正则表达式——元字符
查看>>
anaconda jupyter
查看>>
AngularJs入门(二)
查看>>
整数转为罗马数字
查看>>
POJ2367 Genealogical tree(拓扑排序)
查看>>
GO语言总结(4)——映射(Map)
查看>>
[题解]UVA10129 Play on Words
查看>>
docker
查看>>
css使图片变成黑白效果
查看>>
软件需求十步走读书笔记3
查看>>
电信SMS短信SOAP发送格式(C#手工组成.)
查看>>
Nginx配置之rewrite、proxy_pass、upstream、location
查看>>
c#学习笔记线程
查看>>
Android批量图片加载经典系列——afinal框架实现图片的异步缓存加载
查看>>
CentOS7 Failed to start LSB: Bring up/down解决方法
查看>>