基本
Spring Data 提供了复杂的支持,可以透明地跟踪谁创建或更改了实体以及更改发生的时间。若要从该功能中受益,必须为实体类配备审计元数据,这些元数据可以使用注释或通过实现接口来定义。 此外,必须通过注释配置或 XML 配置启用审核,以注册所需的基础结构组件。 有关配置示例,请参阅特定于商店的部分。
不需要仅跟踪创建和修改日期的应用程序确实会使其实体实现 |
基于注释的审计元数据
我们提供并捕获创建或修改实体的用户,以及捕获更改发生的时间。@CreatedBy
@LastModifiedBy
@CreatedDate
@LastModifiedDate
class Customer {
@CreatedBy
private User user;
@CreatedDate
private Instant createdDate;
// … further properties omitted
}
如您所见,可以有选择地应用注释,具体取决于要捕获的信息。
这些注释指示在进行更改时进行捕获,可用于 JDK8 日期和时间类型、、 以及旧版 Java 和 类型的属性。long
Long
Date
Calendar
审核元数据不一定需要位于根级实体中,但可以添加到嵌入式实体中(取决于使用的实际存储),如下面的代码片段所示。
class Customer {
private AuditMetadata auditingMetadata;
// … further properties omitted
}
class AuditMetadata {
@CreatedBy
private User user;
@CreatedDate
private Instant createdDate;
}
AuditorAware
如果您使用 或 ,则审计基础结构需要以某种方式了解当前主体。为此,我们提供了一个 SPI 接口,您必须实现该接口,以告诉基础设施与应用程序交互的当前用户或系统是谁。泛型类型定义属性批注的类型或必须是哪种类型。@CreatedBy
@LastModifiedBy
AuditorAware<T>
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
使用响应式基础结构时,您可能希望利用上下文信息来提供或信息。
我们提供了一个SPI接口,您必须实现该接口,以告诉基础设施与应用程序交互的当前用户或系统是谁。泛型类型定义属性批注的类型或必须是哪种类型。@CreatedBy
@LastModifiedBy
ReactiveAuditorAware<T>
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
UserDetails
UserDetailsService
UserDetails
Authentication
不需要仅跟踪创建和修改日期的应用程序确实会使其实体实现 |