您现在的位置是:主页 > Web前端技术 > Web前端技术
如何实现Spring事件发布监听、顺序监听和异步监听开发技术
IDCBT2021-12-28【服务器技术】人已围观
简介这篇文章给大家分享的是有关如何实现Spring事件发布监听、顺序监听和异步监听的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。 1. Spring的事件通知
这篇文章给大家分享的是有关如何实现Spring事件发布监听、顺序监听和异步监听的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。
- 1. Spring的事件通知
Spring的事件通知本质上就是发布-订阅,即生产者-消费者;体现了观察者设计模式或者回调通知,那么Spring的事件是如何使用的?
有3要素:发布者-->事件-->监听者
2. Spring事件通知使用Spring的事件必须依赖Spring容器,所以我在写demo的时候,需要Spring-boot-starter。
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> <version>2.1.1.RELEASE</version> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.18.4</version> </dependency> </dependencies>2.1 Spring的事件
Spring的事件定义在ApplicationEvent类中,我们可以根据自己的需要自定义事件实体javabean。
@Data public class TestSpringEvent extends ApplicationEvent { /** * Create a new ApplicationEvent. * * @param source the object on which the event initially occurred (never {@code null}) */ public TestSpringEvent(Object source) { super(source); } private Integer code; private String message; }
跟踪源码:
public abstract class ApplicationEvent extends EventObject { /** use serialVersionUID from Spring 1.2 for interoperability. */ private static final long serialVersionUID = 7099057708183571937L; /** System time when the event happened. */ private final long timestamp; /** * Create a new ApplicationEvent. * @param source the object on which the event initially occurred (never {@code null}) */ public ApplicationEvent(Object source) { super(source); this.timestamp = System.currentTimeMillis(); } /** * Return the system time in milliseconds when the event happened. */ public final long getTimestamp() { return this.timestamp; } }标签:很赞哦! ()