1、监听的组成
要想顺利的创建监听器,并起作用,这个过程中需要这样几个角色:
- 事件(event)可以封装和传递监听器中要处理的参数,如对象或字符串,并作为监听器中监听的目标。
- 监听器(listener)具体根据事件发生的业务处理模块,这里可以接收处理事件中封装的对象或字符串。
- 事件发布者(publisher)事件发生的触发者。
2、事件的定义
我们先定义一个时间,继承org.springframework.context.ApplicationEvent的ApplicationEvent
import org.springframework.context.ApplicationEvent;
public class EventLearn extends ApplicationEvent {
private String address;
private String text;
//source 发生事件的对象
public EventLearn(Object source, String address, String text) {
super(source);
this.address = address;
this.text = text;
}
public String getAddress() {
return address;
}
public String getText() {
return text;
}
}
3、非注解监听器:
继承import org.springframework.context.ApplicationListener
参数使用我们自定义的事件EventLearn即可
此处是instanceof用于判断类型,即传入的参数eventLearn是否是EventLearn类型
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;
@Component
public class ApplicationListenerLearn implements ApplicationListener<Ev

本文详细介绍了在Spring Boot中如何使用监听器(Listener)监听事件,从事件定义、非注解监听器到注解监听器和异步监听。通过实例展示了事件的发布与接收过程,以及如何通过@Async实现异步监听。
spring中如何使用监听器(Listener)监听事件,完整例子&spm=1001.2101.3001.5002&articleId=107481601&d=1&t=3&u=543ef68851cd4da4873308548e7a8c23)
8797

被折叠的 条评论
为什么被折叠?



