乐趣区

Spring-监听事件简明使用

步骤

  1. 定义事件发布器,需要实现 ApplicationEventPublisherAware 接口
  2. 定义事件监听器,需要继承 ApplicationEvent 类
  3. 定义响应事件,需要继承 ApplicationListener<T> 接口

定义事件发布器,ApplicationEventPublisherAware

@Component
public class EventDistributor implements ApplicationEventPublisherAware {

    private static ApplicationEventPublisher applicationEventPublisher;

    @Override
    public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {EventDistributor.applicationEventPublisher = applicationEventPublisher;}

  /**
     * 发布同步事件
     * @param event 事件主题
     */
    public static void publishEvent(ApplicationEvent event) {
        try {applicationEventPublisher.publishEvent(event);
        }catch (Exception e){e.printStackTrace();
            System.out.println("事件发布成功,有部分执行失败");
        }
    }

    /**
     * 发布异步事件,会等待当前事务提交完成后再进行事件发布
     * @param event 事件主题
     */
    public static void publishTransactionSyncEvent(ApplicationEvent event) {TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
            @Override
            public void afterCommit() {
              try{applicationEventPublisher.publishEvent(event);
              }catch (Exception e){e.printStackTrace();
              }
            }
        });
    }
}

定义事件监听器,ApplicationEvent

public class TicketAddEvent extends ApplicationEvent {public TicketAddEvent(ClienteleTicketMessage userTicketMessage) {super(userTicketMessage);
    }

}

在需要被监听处使用:

EventDistributor.publishEvent(new TicketAddEvent( 参数)); 

定义响应事件,ApplicationListener

@Component
public class TicketOverviewListener implements ApplicationListener<TicketAddEvent> {
    @Async// 异步
    @Override
    public void onApplicationEvent(TicketAddEvent ticketAddEvent) {ClienteleTicketMessage userTicketMessage = (ClienteleTicketMessage) ticketAddEvent.getSource();// 接受参数
        响应逻辑
}

监听完成

退出移动版