稽核

基礎

Spring Data 提供了精密的支援,以透明地追蹤誰建立或變更了實體,以及變更發生的時間。要從該功能中受益,您必須為您的實體類別配備稽核元數據,可以使用註解或實作介面來定義。此外,必須透過註解組態或 XML 組態啟用稽核,以註冊所需的基礎架構組件。請參閱特定於商店的部分以獲取組態範例。

僅追蹤建立和修改日期的應用程式不需要使其應用程式實作 AuditorAware

基於註解的稽核元數據

我們提供 @CreatedBy@LastModifiedBy 來捕獲建立或修改實體的用戶,以及 @CreatedDate@LastModifiedDate 來捕獲變更發生的時間。

已稽核的實體
class Customer {

  @CreatedBy
  private User user;

  @CreatedDate
  private Instant createdDate;

  // … further properties omitted
}

如您所見,可以根據您要捕獲的資訊有選擇性地應用註解。指示捕獲何時進行變更的註解可以用於 JDK8 日期和時間類型、longLong 和舊版 Java DateCalendar 類型的屬性。

稽核元數據不一定需要存在於根級別實體中,但可以添加到嵌入式實體中(取決於實際使用的商店),如下面的程式碼片段所示。

嵌入式實體中的稽核元數據
class Customer {

  private AuditMetadata auditingMetadata;

  // … further properties omitted
}

class AuditMetadata {

  @CreatedBy
  private User user;

  @CreatedDate
  private Instant createdDate;

}

基於介面的稽核元數據

如果您不想使用註解來定義稽核元數據,您可以讓您的網域類別實作 Auditable 介面。它公開了所有稽核屬性的 setter 方法。

AuditorAware

如果您使用 @CreatedBy@LastModifiedBy,稽核基礎架構需要以某種方式意識到當前主體。為此,我們提供了一個 AuditorAware<T> SPI 介面,您必須實作該介面以告知基礎架構誰是當前用戶或與應用程式互動的系統。泛型類型 T 定義了以 @CreatedBy@LastModifiedBy 註解的屬性必須是什麼類型。

以下範例顯示了介面的實作,該實作使用 Spring Security 的 Authentication 物件

基於 Spring Security 的 AuditorAware 實作
class SpringSecurityAuditorAware implements AuditorAware<User> {

  @Override
  public Optional<User> getCurrentAuditor() {

    return Optional.ofNullable(SecurityContextHolder.getContext())
            .map(SecurityContext::getAuthentication)
            .filter(Authentication::isAuthenticated)
            .map(Authentication::getPrincipal)
            .map(User.class::cast);
  }
}

該實作存取 Spring Security 提供的 Authentication 物件,並查找您在 UserDetailsService 實作中建立的自訂 UserDetails 實例。我們在這裡假設您正在透過 UserDetails 實作公開網域用戶,但是根據找到的 Authentication,您也可以從任何地方查找它。

ReactiveAuditorAware

當使用反應式基礎架構時,您可能希望使用上下文資訊來提供 @CreatedBy@LastModifiedBy 資訊。我們提供了一個 ReactiveAuditorAware<T> SPI 介面,您必須實作該介面以告知基礎架構誰是當前用戶或與應用程式互動的系統。泛型類型 T 定義了以 @CreatedBy@LastModifiedBy 註解的屬性必須是什麼類型。

以下範例顯示了介面的實作,該實作使用反應式 Spring Security 的 Authentication 物件

基於 Spring Security 的 ReactiveAuditorAware 實作
class SpringSecurityAuditorAware implements ReactiveAuditorAware<User> {

  @Override
  public Mono<User> getCurrentAuditor() {

    return ReactiveSecurityContextHolder.getContext()
                .map(SecurityContext::getAuthentication)
                .filter(Authentication::isAuthenticated)
                .map(Authentication::getPrincipal)
                .map(User.class::cast);
  }
}

該實作存取 Spring Security 提供的 Authentication 物件,並查找您在 UserDetailsService 實作中建立的自訂 UserDetails 實例。我們在這裡假設您正在透過 UserDetails 實作公開網域用戶,但是根據找到的 Authentication,您也可以從任何地方查找它。