@AfterReturning is a Spring AOP annotation that marks a method as advice which runs after a matched method returns normally, meaning it did not throw an exception. The advice can read the returned value, so it suits logging results, auditing, metrics and notifications that should only happen on success.
It cannot change the return value or stop the call, because the target method has already finished. For that you need @Around advice.
Spring AOP supports several advice types. @AfterReturning sits in the order of execution like this:
| Advice | Runs |
|---|---|
@Before | Before the method |
@AfterReturning | After the method returns normally |
@AfterThrowing | After the method throws an exception |
@After | After the method, always (finally semantics) |
@Around | Around the method, controls the call |
If the target method throws, @AfterReturning advice is skipped. If you need code to run in both cases, use @After.
In Spring Boot, add the AOP starter. It brings in Spring AOP and AspectJ's annotations and weaver, and enables proxy-based AOP automatically.
In a plain Spring application, add @EnableAspectJAutoProxy to a configuration class. The aspect itself must be a Spring bean, for example annotated with @Component.
The expression execution(* com.example.service.OrderService.placeOrder(..)) selects the placeOrder method of OrderService with any return type and any arguments. The JoinPoint parameter, always the first parameter if present, gives access to the signature, the target and the arguments.
Use returning to bind the result to an advice parameter. The parameter name must match the attribute value.
The parameter type also acts as a filter. If you declare Order result, the advice only runs when the method returns an Order (or a subtype). A void method binds null for an Object parameter.
Name a pointcut once and reuse it:
You can also match methods that carry a custom annotation, which keeps the aspect decoupled from package names:
final classes and methods cannot be proxied with CGLIB subclassing.@Around when you intend to change the result.@After runs whether the method returns or throws, like a finally block. @AfterReturning runs only after a normal return and can read the result.
No. The caller receives the original value. Use @Around to modify or replace it.
Common causes are a missing @Component or @Aspect, a pointcut that does not match, self-invocation that skips the proxy, or the target method throwing an exception.
Yes. The advice runs after the method completes, and a returning parameter of type Object receives null.
@AfterReturning runs advice after a method completes without an exception and can capture the result through the returning attribute. Use it for success-only logging, auditing and metrics, remember that Spring AOP works through proxies, and choose @Around when you need to alter the call or its result.