Spring Boot 之事件(Event)

Spring 官方文檔翻譯如下 :

ApplicationContext 通過 ApplicationEvent 類和 ApplicationListener 接口進行事件處理。 如果將實現 ApplicationListener 接口的 bean 注入到上下文中,則每次使用 ApplicationContext 發布 ApplicationEvent 時,都會通知該 bean。 本質上,這是標準的觀察者設計模式。

Spring的事件(Application Event)其實就是一個觀察者設計模式,一個 Bean 處理完成任務后希望通知其它 Bean 或者說 一個Bean 想觀察監聽另一個Bean的行為。

Spring 事件只需要幾步:

  • 自定義事件,繼承 ApplicationEvent
  • 定義監聽器,實現 ApplicationListener 或者通過 @EventListener 注解到方法上
  • 定義發布者,通過 ApplicationEventPublisher

代碼示例:

1. 自定義Event

@Data
public class DemoEvent extends ApplicationEvent {
    private Long id;
    private String message;

    public DemoEvent(Object source, Long id, String message) {
        super(source);
        this.id = id;
        this.message = message;
    }
}

2. 監聽器

  • 實現ApplicationListener 接口

@Component
public class DemoListener implements ApplicationListener<DemoEvent> {

    @Override
    public void onApplicationEvent(DemoEvent demoEvent) {
        System.out.println(">>>>>>>>>DemoListener>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
        System.out.println("收到了:" + demoEvent.getSource() + "消息;時間:" + demoEvent.getTimestamp());
        System.out.println("消息:" + demoEvent.getId() + ":" + demoEvent.getMessage());
    }
}

泛型為需要監聽的事件類型

  • @EventListener
@Component
public class DemoListener2 {

    @EventListener
    public void onApplicationEvent(DemoEvent demoEvent) {
        System.out.println(">>>>>>>>>DemoListener2>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
        System.out.println("收到了:" + demoEvent.getSource() + "消息;時間:" + demoEvent.getTimestamp());
        System.out.println("消息:" + demoEvent.getId() + ":" + demoEvent.getMessage());
    }
}

參數為需要監聽的事件類型

3. 消息發布者

@Component
public class DemoPublisher {

    private final ApplicationContext applicationContext;

    @Autowired
    public DemoPublisher(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }

    public void publish(long id, String message) {
        applicationContext.publishEvent(new DemoEvent(this, id, message));
    }

}

4. 測試方法

@Test
public void publisherTest() {
    demoPublisher.publish(1L, "成功了!");
}

5.結果

>>>>>>>>>DemoListener2>>>>>>>>>>>>>>>>>>>>>>>>>>>>
收到了:com.jiuxian.publisher.DemoPublisher@3a62c01e消息;時間:1551762322376
消息:1:成功了!
>>>>>>>>>DemoListener>>>>>>>>>>>>>>>>>>>>>>>>>>>>
收到了:com.jiuxian.publisher.DemoPublisher@3a62c01e消息;時間:1551762322376
消息:1:成功了!

6. 示例源碼

GitHub https://github.com/Zejun-Liu/SpringBoot2.0/tree/master/springboot-event

?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容