Sub topic 11
Around Advice in Depth
Around advice is the most powerful advice type in Spring AOP. It wraps a method call and decides whether the call happens, what arguments it receives, and what the caller gets back.
This chapter assumes you know how to enable AOP, write an @Aspect, and read a basic pointcut expression. It also assumes you know that Spring wraps beans in proxies. Earlier chapters cover each of these.
What around advice can do
@Before and @After advice run beside the target method. Around advice runs instead of it, and the target runs only if your advice asks for it. This gives around advice four abilities that the other advice types lack:
- Run code before and after the target in one method, sharing local variables between the two points.
- Skip the target entirely and return a different result, such as a cached value.
- Change the arguments passed to the target.
- Catch, wrap, retry or suppress exceptions from the target.
Because of this power, prefer the least powerful advice type that does the job. If you only need to log before a call, use @Before. It cannot forget to call the target, and it cannot change the result by accident.
The ProceedingJoinPoint
An around advice method must have a ProceedingJoinPoint as its first parameter. It extends JoinPoint, so it has everything JoinPoint offers, plus proceed().
| Method | Purpose |
|---|---|
| `proceed()` | Calls the next advice in the chain, or the target method. Returns the target's result. |
| `proceed(Object[] args)` | Same, but with replacement arguments. |
| `getArgs()` | Returns the current arguments as an array. |
| `getSignature()` | Returns the method signature, such as its name and declaring type. |
| `getTarget()` | Returns the real object behind the proxy. |
| `getThis()` | Returns the proxy object itself. |
The return type of an around advice method should be Object. Whatever you return becomes the result the caller sees. If the target method returns void, the value you return is discarded. If the target returns a primitive such as int, returning null from the advice causes an AopInvocationException, because Spring cannot unbox it.
The method should declare throws Throwable. proceed() declares it, and checked exceptions thrown by the target must pass through unchanged.
How the call flows
With around advice, the proxy builds a chain. Each around advice calls proceed(), which enters the next link, until the target is reached. The result then travels back out through each link.
Example 1: timing with a finally block
Putting the "after" code in finally makes it run whether the target returns or throws.
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 TimingAspect {
@Around("execution(* com.example.service..*(..))")
public Object time(ProceedingJoinPoint pjp) throws Throwable {
long start = System.nanoTime();
try {
return pjp.proceed();
} finally {
long ms = (System.nanoTime() - start) / 1_000_000;
System.out.println(pjp.getSignature().toShortString() + " took " + ms + " ms");
}
}
}There is no catch block here, so any exception from the target reaches the caller untouched. That is usually what you want.
Example 2: skipping the target with a cache
If the advice never calls proceed(), the target never runs. This aspect caches results for methods marked with a custom annotation.
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@interface Memoized {
}
@Aspect
@Component
class MemoizeAspect {
private final Map<List<Object>, Object> cache = new ConcurrentHashMap<>();
@Around("@annotation(Memoized)")
public Object memoize(ProceedingJoinPoint pjp) throws Throwable {
List<Object> key = Arrays.asList(
pjp.getSignature().toLongString(),
Arrays.asList(pjp.getArgs()));
Object cached = cache.get(key);
if (cached != null) {
return cached;
}
Object result = pjp.proceed();
if (result != null) {
cache.put(key, result);
}
return result;
}
}ConcurrentHashMap rejects null values, so the code stores only non-null results. A real cache would also need eviction. This one grows without bound.
Example 3: changing arguments and handling exceptions
proceed(Object[]) replaces the arguments. The array length and element types must match the target's parameters, or the call fails at runtime.
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 RetryAspect {
@Around("execution(* com.example.client.RemoteClient.*(..))")
public Object retry(ProceedingJoinPoint pjp) throws Throwable {
int attempts = 3;
Throwable last = null;
for (int i = 1; i <= attempts; i++) {
try {
return pjp.proceed();
} catch (java.io.IOException e) {
last = e;
System.out.println("attempt " + i + " failed: " + e.getMessage());
}
}
throw last;
}
}This aspect calls proceed() several times. That is legal for around advice, and it works because each call re-enters the rest of the chain. Retrying is safe only when the target is idempotent. Retrying a payment call without a guard can charge a customer twice.
To rewrite an argument, build a new array from getArgs():
Object[] args = pjp.getArgs();
if (args.length > 0 && args[0] instanceof String s) {
args[0] = s.trim();
}
return pjp.proceed(args);Common errors
- Forgetting to return the result. Writing
pjp.proceed();withoutreturnmakes every caller receivenull. For methods returning primitives this throwsAopInvocationException. - Swallowing exceptions. A
catch (Exception e)that logs and returnsnullhides failures from callers. It can also break@Transactional, because the transaction interceptor never sees the exception and commits. - Declaring the wrong return type. If the advice method returns
voidbut the target returns a value, the caller getsnull. UseObject. - Calling
proceed()twice by accident. The target runs twice. This is a common source of duplicated database writes. - Catching
Exceptionand missingError. Declarethrows Throwable, and let errors propagate. - Assuming the advice sees self-invocation. Calls from one method to another in the same bean bypass the proxy, so around advice never runs for them.
Choosing around advice
Exercise
An around advice method is declared as public void log(ProceedingJoinPoint pjp) throws Throwable { pjp.proceed(); } and applied to a service method that returns a String. What do callers receive, and how do you fix it?
Show answer
Callers receive null. The advice calls the target, but its void return type means no result flows back to the proxy. Change the return type to Object and write return pjp.proceed();.
Exercise
You write an around advice that wraps pjp.proceed() in try { ... } catch (Exception e) { log.error("failed", e); return null; } and apply it to a @Transactional service method. Why is this risky?
Show answer
The exception never reaches the transaction interceptor, so the transaction commits instead of rolling back, and the caller receives null as if the call had succeeded. Rethrow the exception after logging it.