台湾多地大停电,龙珠af,对外经贸大学吧
1.事件(applicationevent)
applicationevent 是所有事件对象的父类。applicationevent 继承自 jdk 的 eventobject, 所有的事件都需要继承 applicationevent, 并且通过source得到事件源。
下列描述了spring提供的内置事件:
2.事件监听(applicationlistener)
applicationlistener 事件监听器,也就是观察者。继承自 jdk 的 eventlistener,该类中只有一个方法 onapplicationevent。当监听的事件发生后该方法会被执行。
3.事件发布(applicationcontext)
applicationcontext 是 spring 中的核心容器,在事件监听中 applicationcontext 可以作为事件的发布者,也就是事件源。因为 applicationcontext 继承自 applicationeventpublisher。在 applicationeventpublisher 中定义了事件发布的方法 — publishevent(object event)
4.事件管理(applicationeventmulticaster)
applicationeventmulticaster 用于事件监听器的注册和事件的广播。监听器的注册就是通过它来实现的,它的作用是把 applicationcontext 发布的 event 广播给它的监听器列表。
@transactionaleventlistener 监听器:如果事件的发布不是在事务(@transactional)范围内,则监听不到该事件,除非将 fallbackexecution 标志设置为 true(@transactionaleventlistener(fallbackexecution = true));如果在事务中,可以选择在事务的哪个阶段来监听事件,默认在事务提交后监听(@transactionaleventlistener(phase = transactionphase.after_completion))。
以上介绍的事件监听都是同步,如果需要开启异步支持的话:
@configuration @enableasync public class asynceventconfiguration implements asyncconfigurer { @override public executor getasyncexecutor() { return executors.newcachedthreadpool(); } }
@component public class myevent extends applicationevent { public myevent(applicationcontext source) { super(source); system.out.println("myevent 构造器执行"); } public void echo() { system.out.println("模拟业务逻辑执行"); } }
@component public class mylistenera implements applicationlistener<myevent> { @override public void onapplicationevent(myevent myevent) { system.out.println("mylistenera"); myevent.echo(); } }
@component public class mylistenerb { @eventlistener public void onapplicationevent(myevent myevent) { system.out.println("mylistenerb"); myevent.echo(); } }
@component public class mypublisher implements applicationcontextaware { private applicationcontext applicationcontext; @override public void setapplicationcontext(applicationcontext applicationcontext) throws beansexception { this.applicationcontext = applicationcontext; } /** * 发布事件 * 监听该事件的监听者都可以获取消息 * * @param myevent */ public void publisherevent(myevent myevent) { system.out.println("---开始发布 myevent 事件---"); applicationcontext.publishevent(myevent); } }
@runwith(springrunner.class) @springboottest public class designpatternsapplicationtests { @autowired private mypublisher mypublisher; @autowired private myevent myevent; @test public void contextloads() { mypublisher.publisherevent(myevent); } }
如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复
浅析我对 String、StringBuilder、StringBuffer 的理解
使用IDEA搭建SSM框架的详细教程(spring + springMVC +MyBatis)
Springboot整合freemarker 404问题解决方案
引入mybatis-plus报 Invalid bound statement错误问题的解决方法
网友评论