Spring 事件

事件
Spring 的默认事件是用来监听容器的,有如下事件:ContextStartedEvent、ContextStoppedEvent、ContextClosedEvent、ContextRefreshedEvent,分别表示容器启动、停止、关闭和刷新事件,监听的话想对简单,实现 ApplicationListener 接口或者在某个 Bean 的方法上增加 @EventListener 注解。

/**
 * @author wangzhi
 */
@Component
@Order(1)
public class ContextClosedEventListener implements ApplicationListener<ContextClosedEvent> {
    @Override
    public void onApplicationEvent(ContextClosedEvent event) {
        System.out.println("ContextClosedEventListener ContextClosedEvent");
    }
}


/**
 * @author wangzhi
 */
@Component
public class ContextClosedEventAnnotationListener {

    @Order(2)
    @EventListener
    public void onEvent(ContextClosedEvent event) {
        System.out.println("ContextClosedEventAnnotationListener ContextClosedEvent");
    }

}

自定义监听的步骤:

  1. 定义自己的事件,也就是 Event,需要继承 ApplicationEvent
  2. 定义自己的事件发布器,需要实现 ApplicationEventPublisherAware
  3. 监听事件,处理自己的业务逻辑
    代码如下:
/**
 * 飞书接口异常事件
 * @author wangzhi
 */
public class FeiShuExceptionEvent extends ApplicationEvent {

    public FeiShuExceptionEvent(Object source) {
        super(source);
    }
    
}



/**
 * 事件发布器
 * @author wangzhi
 */
@Component
public class FeiShuEventPublisher implements ApplicationEventPublisherAware {

    private ApplicationEventPublisher publisher;

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

    public void fire() {
        publisher.publishEvent(new FeiShuExceptionEvent("fei shu exception"));
    }

}


/**
 * 飞书异常事件监听器
 * @author wangzhi
 */
@Component
public class FeiShuExceptionListener {

    @EventListener
    public void onEvent(FeiShuExceptionEvent feiShuExceptionEvent) {
        // 处理自己的业务,可以给相关负责人发送消息什么的
        System.out.println("FeiShuExceptionEvent source:" + feiShuExceptionEvent.getSource());
    }
}

发布器如果要静态使用,参考如下:

/**
 * 发布器
 * @author wangzhi
 */
@Component
public class FeiShuExceptionPublisher  implements ApplicationEventPublisherAware {

    private static ApplicationEventPublisher publisher;

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

    public static void fireEvent(FeiShuExceptionEvent event) {
        FeiShuExceptionPublisher.publisher.publishEvent(event);
    }
}

参考:《学透 Spring》

posted @ 2023-03-28 18:55  庄子游世  阅读(112)  评论(0)    收藏  举报