Aspect-Oriented Programming (AOP) & custom annotations
How @Audited, @RequirePermission and @RequireStepUpMfa work. Pointcuts, advice, proxies, and when AOP is the right tool.
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,@Afteror@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
module/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.
shared/aspect/AuditAspect.java · AccountService.javaReport-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.
accesscontrol/web/PermissionAspect.javaAuthorization 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 |
Related concepts you must know
- Self-invocation.
this.audited()bypasses the proxy, so no advice runs. - Only public methods are advised by default with proxy-based AOP.
- Ordering. Use
@Orderwhen several aspects apply, e.g. security before audit before transaction. - ThreadLocal context.
AuditContextandTenantContextmust be cleared infinally, otherwise a pooled thread leaks state into the next request. SperoTek does this. - Decorator / Proxy patterns (GoF) are the OO ideas underneath.