【发布时间】:2020-01-21 09:43:23
【问题描述】:
我有几个实体需要审核。审计是通过使用以下 JPA 事件侦听器实现的。
public class AuditListener {
@PrePersist
@Transactional(readOnly = true, propagation = Propagation.REQUIRES_NEW)
public void setCreatedOn(Auditable auditable) {
User currentUser = getCurrentUser();
Long entityId = auditable.getId();
Audit audit;
if (isNull(entityId)) {
audit = getCreatedOnAudit(currentUser);
} else {
audit = getUpdatedOnAudit(auditable, currentUser);
}
auditable.setAudit(audit);
}
@PreUpdate
@Transactional(readOnly = true, propagation = Propagation.REQUIRES_NEW)
public void setUpdatedOn(Auditable auditable) {
User currentUser = getCurrentUser();
auditable.setAudit(getUpdatedOnAudit(auditable, currentUser));
}
private Audit getCreatedOnAudit(User currentUser) {
return Audit.builder()
.userCreate(currentUser)
.dateCreate(now())
.build();
}
private Audit getUpdatedOnAudit(Auditable auditable, User currentUser) {
AuditService auditService = BeanUtils.getBean(AuditService.class);
Audit audit = auditService.getAudit(auditable.getClass().getName(), auditable.getId());
audit.setUserUpdate(currentUser);
audit.setDateUpdate(now());
return audit;
}
private User getCurrentUser() {
String userName = "admin";
UserService userService = BeanUtils.getBean(UserService.class);
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if (nonNull(auth)) {
Object principal = auth.getPrincipal();
if (principal instanceof UserDetails) {
userName = ((UserDetails)principal).getUsername();
}
}
return userService.findByLogin(userName);
}
}
在测试环境(单元测试,e2e)中,我希望能够手动设置审核。
这可能吗?我之前曾尝试用 Spring AOP 解决这个问题,但不幸的是没有成功。我认为,Spring AOP 可以允许通过在切入点中使用各种组合来选择性地设置审计:
- Audit for cascade saving by using Spring AOP
- Why aspect not triggered for owner side in OneToOne relationship?
有没有办法通过使用 JPA 功能选择性地设置审计?
【问题讨论】:
-
简单地模拟/监视
UserService(使用@MockBean或测试上下文的简单bean 定义覆盖)怎么样?您应该能够以类似的方式覆盖创建/修改时间,使用now(clock)而不是now()并注入Clock,然后您可以使用模拟/固定瞬间覆盖其提供程序定义以进行测试。顺便说一句,你不需要BeanUtils.getBean(UserService.class),Spring 支持 JPA 侦听器中的依赖注入
标签: java spring-boot jpa spring-data-jpa auditing