Video in progress

Strong Middle 🌱 Spring

How do you build audit logging with an aspect, marking methods with your own @Audited annotation?

You write the annotation with RUNTIME retention, bind it as an advice parameter in the aspect with the @annotation(audited) pointcut, and record the arguments, result or exception. The proxy limitations (self-invocation, non-public methods) apply here too.

📖 Answer

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Audited {
    String action();
}

@Aspect
@Component
class AuditAspect {
    private final AuditLog audit;
    AuditAspect(AuditLog audit) { this.audit = audit; }

    @AfterReturning(pointcut = "@annotation(audited)", returning = "result")
    void ok(JoinPoint jp, Audited audited, Object result) {
        audit.write(audited.action(), currentUser(), mask(jp.getArgs()), "OK");
    }

    @AfterThrowing(pointcut = "@annotation(audited)", throwing = "ex")
    void failed(JoinPoint jp, Audited audited, Exception ex) {
        audit.write(audited.action(), currentUser(), mask(jp.getArgs()), ex.getClass().getSimpleName());
    }
}

Usage: @Audited(action = "REFUND") public void refund(long id, BigDecimal sum).

The name inside @annotation(audited) is lowercase because it's the name of the advice parameter. Spring takes the annotation type from the parameter type and gives you the value directly, so you don't need to use reflection with getAnnotation.

Common problems:

  • if you don't specify the retention, the default is CLASS: the annotation isn't visible at runtime and the aspect never fires;
  • put the annotation on the method in the implementation class: in Java, method annotations aren't inherited from an interface, and the pointcut may not find it;
  • writing jp.getArgs() raw puts passwords or card numbers into the audit table, so masking is a must;
  • if the audit record is inside the main transaction, it disappears on rollback too. If you need "keep the failed attempt as well", use a separate transaction (REQUIRES_NEW) or an asynchronous write.

When several aspects apply to one method, set the order explicitly with @Order.