Spring审计
外观
Spring审计是Spring框架中用于自动追踪实体变更(如创建时间、修改时间、操作用户等)的机制,常用于记录数据的历史操作。它通过注解和接口实现自动化管理,适用于需要合规性检查、版本控制或操作日志的场景。
核心概念[编辑 | 编辑源代码]
Spring审计分为两类:
- 时间审计:记录实体的创建时间(
@CreatedDate
)和最后修改时间(@LastModifiedDate
)。 - 用户审计:记录实体的创建者(
@CreatedBy
)和最后修改者(@LastModifiedBy
)。
审计数据通常存储在实体类的字段中,由Spring Data自动填充。
实现步骤[编辑 | 编辑源代码]
1. 启用审计功能[编辑 | 编辑源代码]
在配置类中添加@EnableJpaAuditing
:
@Configuration
@EnableJpaAuditing
public class AuditConfig {
@Bean
public AuditorAware<String> auditorProvider() {
return () -> Optional.of("currentUser"); // 模拟当前用户
}
}
2. 定义审计字段[编辑 | 编辑源代码]
实体类中添加审计字段并标注注解:
@Entity
@EntityListeners(AuditingEntityListener.class)
public class Product {
@Id
private Long id;
@CreatedDate
private LocalDateTime createdAt;
@LastModifiedDate
private LocalDateTime updatedAt;
@CreatedBy
private String createdBy;
@LastModifiedBy
private String updatedBy;
}
3. 操作示例[编辑 | 编辑源代码]
保存实体时,字段自动填充:
Product product = new Product();
productRepository.save(product);
// 输出:createdAt=2023-10-01T10:00, createdBy=currentUser
实际案例[编辑 | 编辑源代码]
场景:电商订单追踪 审计字段记录订单创建时间和修改人,便于纠纷排查:
高级配置[编辑 | 编辑源代码]
自定义审计逻辑[编辑 | 编辑源代码]
通过实现AuditorAware<T>
接口动态获取当前用户(如从Spring Security上下文):
public class SecurityAuditorAware implements AuditorAware<String> {
@Override
public Optional<String> getCurrentAuditor() {
return Optional.ofNullable(SecurityContextHolder.getContext())
.map(SecurityContext::getAuthentication)
.map(Authentication::getName);
}
}
时区处理[编辑 | 编辑源代码]
使用@DateTimeFormat
定义时间格式:
@CreatedDate
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm")
private LocalDateTime createdAt;
数学表示[编辑 | 编辑源代码]
审计时间可视为函数:
总结[编辑 | 编辑源代码]
Spring审计通过自动化记录关键操作信息,显著减少手动编码量。结合Spring Security可实现完整的操作追踪体系,适用于金融、医疗等合规性要求高的领域。