审计
基础知识
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
,审计基础设施需要以某种方式知晓当前的 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
对象,并查找您在 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
,您也可以从任何地方查找它。