1.创建事件类
@Data
public class MyEvent{
private String eventId;
private String title;
private String content;
public MyEvent() {
this.eventId = UUID.randomUUID().toString();
}
}
2. 创建事件监听类与方法
@EventListener注释方法的所属类必须是被Spring管理的Bean,否则事件监听方法不会生效
// @EventListener注释方法的所属类必须是被Spring管理的Bean,否则事件监听方法不会生效
@Component
public class MyListener {
@Async
@Order(Ordered.HIGHEST_PRECEDENCE)
@EventListener(MyEvent.class)
public void myEventHandler(MyEvent event) {
// 处理事件的方法块
System.out.println("接收到了MyEvent事件,开始处理...");
System.out.println(event.toString());
System.out.println("事件处理完毕!");
}
}
3. 发布事件
@Service
public class MyService {
@Resource
private ApplicationEventPublisher publisher;
public String service() {
System.out.println("开始处理服务请求...");
String status = "START";
publisher.publishEvent(new MyEvent());
System.out.println("服务处理完毕!");
return "OK";
}
}
4. 测试
public static void main(String[] args) {
ApplicationContext ctx = SpringApplication.run(UserCenterApplication.class, args);
MyService service = ctx.getBean(MyService.class);
service.service();
}
测试结果:
开始处理服务请求...
接收到了MyEvent事件,开始处理...
MyEvent(eventId=6ec5d9eb-f33e-4198-a774-73d0c8c5cc4d, title=null, content=null)
事件处理完毕!
服务处理完毕!