I have several entities that need to be audited. Auditing is implemented by using the following JPA event listener.
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);
}
}
In a test environment(unit tests, e2e) for some tests I want to be able to manually set the audit.
Is that possible? I have previously tried to solve this problem with Spring AOP but unfortunately without success. I think, that Spring AOP could allow selectively set the audit by using various combinations in pointcuts:
- Audit for cascade saving by using Spring AOP
- Why aspect not triggered for owner side in OneToOne relationship?
Is there a way to selectively set auditing by using JPA features?