稽核
基礎
Spring Data 提供精密的支援,以透明地追蹤實體的建立者、變更者以及變更發生的時間。要從此功能獲益,您必須為實體類別配備稽核中繼資料,這些中繼資料可以使用註解或實作介面來定義。此外,必須透過註解組態或 XML 組態啟用稽核,以註冊所需基礎架構元件。請參閱特定商店章節以取得組態範例。
僅追蹤建立和修改日期的應用程式不需要使其實體實作 |
基於註解的稽核中繼資料
我們提供 @CreatedBy
和 @LastModifiedBy
來捕捉建立或修改實體的使用者,以及 @CreatedDate
和 @LastModifiedDate
來捕捉變更發生的時間。
class Customer {
@CreatedBy
private User user;
@CreatedDate
private Instant createdDate;
// … further properties omitted
}
如您所見,註解可以選擇性地應用,具體取決於您想要捕捉的資訊。指示捕捉變更時間的註解可以用於 JDK8 日期和時間類型、long
、Long
和舊版 Java Date
和 Calendar
類型的屬性。
稽核中繼資料不一定需要存在於根層級實體中,但可以新增至嵌入式實體(取決於實際使用的商店),如下面的程式碼片段所示。
class Customer {
private AuditMetadata auditingMetadata;
// … further properties omitted
}
class AuditMetadata {
@CreatedBy
private User user;
@CreatedDate
private Instant createdDate;
}
AuditorAware
如果您使用 @CreatedBy
或 @LastModifiedBy
,稽核基礎架構需要以某種方式感知目前的主體。為此,我們提供了一個 AuditorAware<T>
SPI 介面,您必須實作該介面,以告知基礎架構誰是目前與應用程式互動的使用者或系統。泛型類型 T
定義了使用 @CreatedBy
或 @LastModifiedBy
註解的屬性必須是什麼類型。
以下範例顯示了介面的實作,該實作使用 Spring Security 的 Authentication
物件
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
物件
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
,您也可以從任何地方查閱它。