概述

在编写代码的时候,比如我删除一篇文章,这个时候,如果我想做些额外的逻辑,这是就需要修改删除部分的代码。spring 提供了事件机制更优雅的实现这个,用户只需要实现事件监听即可。

代码实现

注入发布者

public class KnowledgeBaseService implements ApplicationEventPublisherAware {

  private final KnowledgeBaseArticleRepository knowledgeBaseArticleRepository;
  private ApplicationEventPublisher applicationEventPublisher;

  public KnowledgeBaseService(
      KnowledgeBaseArticleRepository knowledgeBaseArticleRepository) {
    this.knowledgeBaseArticleRepository = knowledgeBaseArticleRepository;
  }
  // 注入事件发布者
  @Override
  public void setApplicationEventPublisher(
      @NotNull ApplicationEventPublisher applicationEventPublisher) {
    this.applicationEventPublisher = applicationEventPublisher;
  }

发布事件

public void deleteArticle(UUID id) {
    knowledgeBaseArticleRepository.findById(id).ifPresent(article -> {
      knowledgeBaseArticleRepository.delete(article);
      applicationEventPublisher.publishEvent(
          new KnowledgeBaseArticleDeletedEvent(
              article.toKnowledgeBaseArticle()));
    });
  }

处理事件

@EventListener
  @Async
  public void handleArticleDeleted(KnowledgeBaseArticleDeletedEvent event) {
    documentLoader.deleteDocumentsByArticle(
        (KnowledgeBaseArticle) event.getSource());
  }
posted on 2024-06-19 15:05  自由港  阅读(6)  评论(0编辑  收藏  举报