Sub topic 11
Around advice in depth
This chapter assumes you can write a basic @Aspect and a pointcut expression, and that you know Spring wraps beans in proxies. It looks at what makes @Around different from the other advice types.
What around advice controls
@Before, @After and the other advice types run beside the target method. @Around runs instead of it. Spring calls your advice, and your advice decides whether the target runs, how often, with which arguments, and what the caller gets back.
The advice receives a ProceedingJoinPoint. Its proceed() method calls the next advice in the chain, or the target method if no advice is left.
The rules of an around method
- The method must return
Object, so it can pass the target's result through. - It should declare
throws Throwable, becauseproceed()rethrows whatever the target throws. - If you never call
proceed(), the target does not run. This is how caching and access-control aspects short-circuit a call. - If you do not return the result of
proceed(), the caller receivesnull. For a method returning a primitive such asint, anullresult causes anAopInvocationException. - You can call
proceed()more than once. Each call runs the target again.
Calling proceed more than once
A retry aspect uses the last rule. The advice catches a specific failure and tries again.
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 RetryAspect {
@Around("execution(* com.example.client..*(..))")
public Object retry(ProceedingJoinPoint pjp) throws Throwable {
int attempts = 3;
IllegalStateException last = null;
for (int i = 1; i <= attempts; i++) {
try {
return pjp.proceed();
} catch (IllegalStateException e) {
last = e;
System.out.println(pjp.getSignature().toShortString()
+ " failed, attempt " + i + " of " + attempts);
}
}
throw last;
}
}Only IllegalStateException triggers a retry. Any other exception propagates immediately, which is usually what you want.
Changing arguments
proceed(Object[] args) replaces the arguments the target receives. The array must match the method's parameter count and types.
@Around("execution(* com.example.service.GreetingService.greet(..))")
public Object normalize(ProceedingJoinPoint pjp) throws Throwable {
Object[] args = pjp.getArgs();
args[0] = ((String) args[0]).trim();
return pjp.proceed(args);
}Common mistakes
- Swallowing exceptions. A
catchblock that logs and returnsnullhides the failure from the caller and from@Transactional, which needs to see the exception to roll back. - Wrapping exceptions. Catching
Throwableand throwingRuntimeExceptionchanges the exception type callers expect. - Skipping
finallyfor cleanup. Timing and resource code belongs infinally, as in theTimingAspectfrom the earlier chapter, so it runs on failure too. - Using
@Aroundwhen a simpler type works. If you only log before a call,@Beforecannot forget to callproceed().
Exercise
An @Around advice method calls pjp.proceed() but ends with "return null;" instead of returning the result. The target method returns a String. What does the caller see, and what happens if the target returns int?
Show answer
For the String method the caller always receives null, because the advice discards the real result. For the int method Spring cannot convert null to a primitive, so it throws an AopInvocationException. Fix it by returning the value that proceed() returned.