BBackend CourseLeroy Labs
0/0
Search the course

Aspect-Oriented Programming (AOP) & custom annotations

How @Audited, @RequirePermission and @RequireStepUpMfa work. Pointcuts, advice, proxies, and when AOP is the right tool.

● intermediateHostel-Web-AppReport-Manager-2IR3D (Kontentt)SperoTek (in dev)

The concept

Some concerns cut across many unrelated methods: auditing, permission checks, timing, retries. Copying audit.record(...) into 70 methods is error-prone. AOP lets you declare the behaviour once and attach it wherever an annotation appears.

Vocabulary:

  • Join point: a point in execution. In Spring AOP that is always a method call on a bean.
  • Pointcut: an expression selecting join points, e.g. @annotation(audited).
  • Advice: the code that runs. It can be @Before, @AfterReturning, @AfterThrowing, @After or @Around (which wraps the call and can change its result).
  • Aspect: a class grouping pointcuts and advice (@Aspect @Component).

Full example: an audit annotation

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

@Aspect
@Component
@RequiredArgsConstructor
class AuditAspect {
    private final AuditLogService auditLogService;

    @Around("@annotation(audited)")
    public Object audit(ProceedingJoinPoint pjp, Audited audited) throws Throwable {
        Object result = pjp.proceed();                  // run the real method
        auditLogService.record(currentUser(), audited.action(),
                               audited.targetType(), extractId(result));
        return result;
    }
}

// usage
@Audited(action = "BOOKING_APPROVED", targetType = "Booking")
public BookingDto approveBooking(UUID id) { /* ... */ }

How it works: proxies

At startup Spring sees that BookingService has a method matched by a pointcut, so it injects a proxy instead of the raw bean. The proxy is a CGLIB subclass, or a JDK dynamic proxy when the bean is used through an interface. Callers talk to the proxy, and the proxy runs the advice before handing the call to the real object.

That is also why @Transactional, @Async, @Cacheable and @PreAuthorize work: they are all built-in aspects.

In your projects

Hostel-Web-Appmodule/audit/AuditAspect.java

@Audited(action, targetType) with @Around("@annotation(audited)") records the actor, role, action, target and an old/new snapshot. The “before” state is passed in via AuditContext.takeOld(), a ThreadLocal-style holder the service fills before mutating.

Report-Manager-2shared/aspect/AuditAspect.java · AccountService.java

Report-Manager-2’s version is more declarative:

@Auditable(action = AuditAction.UPDATE, logBefore = true, logAfter = true,
           entityClass = Account.class, idParameterName = "id")
public AccountResponse update(UUID id, UpdateAccountDto dto) { /* ... */ }

The aspect loads the entity before the call, using idParameterName and entityClass, and again after, so the audit row holds a real diff.

SperoTek (in dev)accesscontrol/web/PermissionAspect.java

Authorization as an aspect:

@Before("@annotation(requirement)")
void check(RequirePermission requirement) {
    if (!TenantContext.current().hasPermission(requirement.value()))
        throw new ApiException(ErrorCode.FORBIDDEN);
}

SperoTek also has @RequireStepUpMfa (StepUpMfaAspect). IR3D has about 148 @RequiresPermission uses plus @ActivityLogged (48) and @Audited (70).

Alternatives

Tool Notes
Spring AOP aspects (yours) Method-level on beans only; simple
Servlet filters / HandlerInterceptor HTTP-level concerns: logging, rate limits, tenant resolution (SperoTek’s TenantResolutionFilter)
JPA entity listeners / Hibernate Envers Automatic entity auditing at the persistence layer
Database triggers Can’t be bypassed even by raw SQL (SperoTek’s append-only audit)
AspectJ compile/load-time weaving Works on private methods and self-calls, but the build is more complex
Explicit calls / decorators Most transparent, but easy to forget
  • Self-invocation. this.audited() bypasses the proxy, so no advice runs.
  • Only public methods are advised by default with proxy-based AOP.
  • Ordering. Use @Order when several aspects apply, e.g. security before audit before transaction.
  • ThreadLocal context. AuditContext and TenantContext must be cleared in finally, otherwise a pooled thread leaks state into the next request. SperoTek does this.
  • Decorator / Proxy patterns (GoF) are the OO ideas underneath.

Check yourself

1. Which advice type can modify the return value?
2. Why must TenantContext be cleared in a finally block?