Sub topic 13
Building an annotation-driven aspect
This chapter assumes you can write a basic @Aspect and read a pointcut expression. You should also know how Spring wraps beans in proxies. Here you will create your own annotation and an aspect that runs wherever the annotation appears.
Why use an annotation as a marker
A package-based pointcut such as execution(* com.example.service..*(..)) ties behavior to where code lives. That is fine for broad concerns like timing. For a narrower concern such as auditing, you want to say "this method, and only this one." A custom annotation does that. The annotation marks the method, and the pointcut finds the mark.
Step 1: Define the annotation
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@interface Audited {
String action();
}RetentionPolicy.RUNTIME is required. With the default retention, the annotation is dropped before runtime and the pointcut can never match it. @Target(ElementType.METHOD) limits the annotation to methods.
Step 2: Write the aspect
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
@Aspect
@Component
class AuditAspect {
@Around("@annotation(audited)")
public Object audit(ProceedingJoinPoint pjp, Audited audited) throws Throwable {
System.out.println("audit start: " + audited.action());
Object result = pjp.proceed();
System.out.println("audit end: " + audited.action());
return result;
}
}The pointcut @annotation(audited) does two jobs. It matches any method carrying @Audited. Because audited is also a parameter name on the advice method, Spring binds the annotation instance to that parameter. The aspect can then read audited.action().
Step 3: Apply it to a bean
import org.springframework.stereotype.Service;
@Service
class PaymentService {
@Audited(action = "refund")
public void refund(String orderId) {
// business logic only
}
}When another bean calls paymentService.refund("A-1"), the call goes through the proxy. The proxy runs AuditAspect.audit, which prints, calls proceed(), then prints again.
Common errors
- Advice never runs. Check that the annotation has
RUNTIMEretention and that the aspect is a Spring bean. Check that AOP is enabled, and that the call comes from another bean. Calls inside the same class skip the proxy. - Binding fails at startup. The name in
@annotation(audited)must match the advice parameter name exactly, and the parameter type must be the annotation type. - The audit end line is missing. In the example above, an exception from
proceed()skips the secondprintln. Wrap it intry/finally, or use@AfterThrowing, if you need it to run on failure.
Exercise
Your @Audited aspect works when a controller calls PaymentService.refund, but not when PaymentService.processBatch calls this.refund(...). Why, and what is one fix?
Show answer
The call through this bypasses the Spring proxy, so no advice runs. Move refund into another bean and inject it, or call it through an injected proxy reference.
Exercise
What happens if Audited is declared without @Retention(RetentionPolicy.RUNTIME)?
Show answer
The annotation is not available at runtime, so @annotation(audited) never matches and the advice never runs.