Sub topic 13
Building an annotation-driven aspect
This chapter assumes you know how to write an @Aspect with @Around advice and a basic pointcut expression, and that you know Spring wraps beans in proxies. Here you will build an aspect that applies behavior wherever a custom annotation appears. That pattern is how @Transactional, @Cacheable and @Async work.
Why annotations instead of package pointcuts
A pointcut like execution(* com.example.service..*(..)) ties the aspect to your package layout. A new service in another package is silently skipped, and a method in the matched package that should be skipped is advised anyway.
An annotation moves that decision to the method. The developer opts in at the place where the behavior matters, and a reader of the method sees that something extra happens. The aspect stays generic.
The annotation
The annotation must be readable at runtime. Without RetentionPolicy.RUNTIME, the compiler drops it from the class file and the pointcut never matches. This is the most common reason an annotation-driven aspect does nothing.
package com.example.audit;
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, ElementType.TYPE})
public @interface Audited {
String action();
}@Target allows the annotation on methods and on classes. The aspect below handles both.
The aspect
Two pointcut designators do the matching:
@annotation(audited)matches a method that carries the annotation. The nameauditedbinds the annotation instance to the advice parameter, so you can readaudited.action().@within(audited)matches any method declared in a class that carries the annotation.
A method inside an annotated class may also carry its own annotation. The second advice excludes such methods, so the call is audited once, using the more specific method-level value.
package com.example.audit;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
@Aspect
@Component
public class AuditAspect {
@Around("@annotation(audited)")
public Object auditMethod(ProceedingJoinPoint pjp, Audited audited) throws Throwable {
return run(pjp, audited);
}
@Around("@within(audited) && !@annotation(com.example.audit.Audited)")
public Object auditClass(ProceedingJoinPoint pjp, Audited audited) throws Throwable {
return run(pjp, audited);
}
private Object run(ProceedingJoinPoint pjp, Audited audited) throws Throwable {
String signature = pjp.getSignature().toShortString();
System.out.println("audit start [" + audited.action() + "] " + signature);
try {
Object result = pjp.proceed();
System.out.println("audit ok [" + audited.action() + "] " + signature);
return result;
} catch (Throwable t) {
System.out.println("audit fail [" + audited.action() + "] " + t);
throw t;
}
}
}The advice rethrows the original exception, so callers see the same failure they would see without the aspect. Returning the result of proceed() is equally important. If you drop it, every advised method returns null.
Running it
This example uses Spring Boot with spring-boot-starter-aop on the classpath, which enables proxy creation automatically.
package com.example.audit;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.stereotype.Service;
@Service
class TransferService {
@Audited(action = "transfer")
public String transfer(String from, String to) {
return from + " -> " + to;
}
public String balance(String account) {
return "balance of " + account;
}
}
@SpringBootApplication
public class AuditDemo {
public static void main(String[] args) {
ConfigurableApplicationContext ctx = SpringApplication.run(AuditDemo.class, args);
TransferService service = ctx.getBean(TransferService.class);
System.out.println(service.transfer("A", "B"));
System.out.println(service.balance("A"));
ctx.close();
}
}Calling transfer prints the start and ok lines around the result. Calling balance prints no audit lines, because it has no annotation.
Details that cause bugs
Parameter name binding
Binding audited by name requires Spring to know the advice parameter names. Compile with -parameters. Spring Boot's Maven and Gradle plugins set this for you. In a plain build, add the flag yourself, or name the parameters explicitly with argNames = "pjp,audited" on the advice annotation. Spring 6.1 and later no longer fall back to reading debug information.
Where the annotation sits
The aspect sees the annotation on the method of the target class. An annotation placed only on an interface method is not guaranteed to match @annotation, and annotations on interfaces are not inherited by implementing classes. Put the annotation on the implementation method or class.
Type-level matching limits
@within matches methods declared in the annotated class. It does not cover methods the class inherits from an unannotated superclass. If you need the runtime type instead, @target(audited) matches when the target object's class carries the annotation, but it needs a runtime check on every call, so it costs more.
The usual proxy limits still apply
Annotation-driven advice runs only when the call passes through the proxy. A call from one method to another on this skips it, and final or private methods cannot be intercepted by a CGLIB proxy. If an @Audited method is called internally, nothing is audited. The earlier chapters on self-invocation and proxy limitations apply unchanged here.
Matching beans outside your control
An annotation pointcut matches any Spring bean whose method has the annotation, in any package. That is the intended benefit. It also means a library class annotated with your annotation gets advised. If you want to limit the scope, combine designators, for example @annotation(audited) && within(com.example..*).
Reading more from the call
Add && args(from, to) to the pointcut when you need arguments, or call pjp.getArgs(). Reading pjp.getSignature() and casting it to MethodSignature gives access to the Method object, which lets you read parameter annotations. Never log argument values that may hold secrets.
Choosing annotation pointcuts
| Approach | Strength | Weakness |
|---|---|---|
| `execution(...)` on packages | No changes to application code | Hidden behavior, breaks when code moves |
| `@annotation` on methods | Explicit and visible, fine-grained | Developers must remember to annotate |
| `@within` on classes | One annotation covers a whole class | Does not reach inherited methods |
Exercise
An aspect uses @Around("@annotation(audited)"). A developer adds @Audited(action = "export") to a method, but nothing is printed. The annotation is declared with @Target(ElementType.METHOD) and no @Retention. Name the likely cause and one other cause that would produce the same symptom.
Show answer
The default retention is CLASS, so the annotation is not visible at runtime and the pointcut never matches. The fix is @Retention(RetentionPolicy.RUNTIME). Another cause is self-invocation: if another method of the same class calls the annotated method through this, the call bypasses the proxy and the advice does not run. The bean might also not be managed by Spring, or the method might be final or private.