事件

編寫 ApplicationListener

您可以子類化一個抽象類,該類監聽這些事件並根據事件型別呼叫相應的方法。為此,請按如下方式覆蓋相關事件的方法

public class BeforeSaveEventListener extends AbstractRepositoryEventListener {

  @Override
  public void onBeforeSave(Object entity) {
    ... logic to handle inspecting the entity before the Repository saves it
  }

  @Override
  public void onAfterDelete(Object entity) {
    ... send a message that this entity has been deleted
  }
}

然而,這種方法需要注意的一點是,它不區分實體型別。您必須自行檢查。

編寫帶註解的處理器

另一種方法是使用帶註解的處理器,它根據領域型別過濾事件。

要宣告處理器,請建立一個POJO並在其上新增 @RepositoryEventHandler 註解。這會告訴 BeanPostProcessor 該類需要被檢查以查詢處理器方法。

一旦 BeanPostProcessor 發現帶有此註解的bean,它會遍歷公開的方法並查詢與相關事件對應的註解。例如,要在帶註解的POJO中處理不同領域型別的 BeforeSaveEvent 例項,您可以按如下方式定義您的類

@RepositoryEventHandler (1)
public class PersonEventHandler {

  @HandleBeforeSave
  public void handlePersonSave(Person p) {
    // … you can now deal with Person in a type-safe way
  }

  @HandleBeforeSave
  public void handleProfileSave(Profile p) {
    // … you can now deal with Profile in a type-safe way
  }
}
1 可以透過使用(例如) @RepositoryEventHandler(Person.class) 來縮小此處理器適用的類型範圍。

您感興趣的領域型別事件將由帶註解方法的第一個引數的型別決定。

要註冊您的事件處理器,要麼用Spring的 @Component 派生註解之一標記該類(以便它可以被 @SpringBootApplication@ComponentScan 發現),要麼在您的 ApplicationContext 中宣告一個帶註解的bean例項。然後,在 RepositoryRestMvcConfiguration 中建立的 BeanPostProcessor 會檢查該bean以查詢處理器並將它們連線到正確的事件。以下示例展示瞭如何為 Person 類建立事件處理器

@Configuration
public class RepositoryConfiguration {

  @Bean
  PersonEventHandler personEventHandler() {
    return new PersonEventHandler();
  }
}
Spring Data REST事件是自定義的Spring應用程式事件。預設情況下,Spring事件是同步的,除非它們跨邊界重新發布(例如發出WebSocket事件或跨執行緒)。
© . This site is unofficial and not affiliated with VMware.