事件

撰寫 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 事件或跨入執行緒)。