ApplicationContext中的事件处理是通过ApplicationEvent类和ApplicationListener接口来提供的,通过ApplicationContext的publishEvent()方法发布到ApplicationListener;
在这里包含三个角色:被发布的事件,事件发布者,事件的监听者。
事件发布者在发布事件的时候->通知事件的监听者。
1.要发布的事件
public class OrderEvent extends ApplicationEvent {
private Order order;
public UseVoucherCodesEvent(Order order) {
super(order);
this.order = order;
}
}
2.发布事件
this.applicationContext.publishEvent(new OrderEvent(order));
3.处理事件
@Slf4j
@Component
@Transactional
public class OrderListener implements ApplicationListener<OrderEvent> {
@Override
public void onApplicationEvent(OrderPayFinishEvent event) {
//todo 处理业务逻辑
}
}
本文详细介绍了Spring框架中事件处理机制的核心概念,包括事件发布、事件监听和事件处理的具体实现方式。通过自定义事件OrderEvent及监听器OrderListener,展示了如何在Spring应用上下文中进行事件的发布与订阅。
762

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



