|
此版本仍在开发中,尚未被视为稳定版。如需最新稳定版,请使用 Spring Data Commons 4.0.4! |
审计
基础
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 类型的属性上。
时间提供实例由 org.springframework.data.auditing.DateTimeProvider 提供。
默认情况下,这是一个 CurrentDateTimeProvider。
在启用审计功能时,可以通过 dateTimeProviderRef 属性进行更改,或者在 AuditingHandler 中提供一个专门的 DateTimeProvider 或 ApplicationContext bean。
审计元数据不一定需要位于根级实体中,也可以添加到嵌入式实体中(具体取决于所使用的实际存储),如下方代码片段所示。
class Customer {
private AuditMetadata auditingMetadata;
// … further properties omitted
}
class AuditMetadata {
@CreatedBy
private User user;
@CreatedDate
private Instant createdDate;
}
AuditorAware
如果您使用了 @CreatedBy 或 @LastModifiedBy 注解,审计基础设施需要以某种方式获知当前的主体(principal)。为此,我们提供了一个 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 对象,并查找你在 UserDetails 实现中创建的自定义 UserDetailsService 实例。我们在此假设你通过 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()
.mapNotNull(SecurityContext::getAuthentication)
.filter(Authentication::isAuthenticated)
.mapNotNull(Authentication::getPrincipal)
.map(User.class::cast);
}
}
该实现会访问 Spring Security 提供的 Authentication 对象,并查找你在 UserDetails 实现中创建的自定义 UserDetailsService 实例。我们在此假设你通过 UserDetails 实现暴露了领域用户,但你也可以根据找到的 Authentication 从任意位置查找该用户。