Spring Aspect AfterReturning advice executes after a matched method execution returns normally with no exception. You can declare this advice using the @AfterReturning annotation. For example, this advice can send email alerts about the successful completion of the target method execution.
@AfterReturning("execution(* com..*(..))") public void afterSuccess() { logger.info("AfterReturning Advice method started : " + joinPoint.getSignature().getName()); SimpleMailMessage simpleMailMessage = new SimpleMailMessage(); message.setFrom("contactus@tedblob.com"); message.setTo("success@tedblob.com"); message.setSubject("Success"); message.setText("The operation is completed successfully and the results are updated to the database"); emailSender.send(message); logger.info("AfterReturning Advice method stopper : " + joinPoint.getSignature().getName()); }
If you require the target method’s return value inside the advice body, then change the @AfterReturning annotation to bind the return value
@AfterReturning(value = "execution(* com..*(..))", returning = "result") public void afterSuccess(JoinPoint joinPoint, Object result) { logger.info("AfterReturning Advice method started : " + joinPoint.getSignature().getName()); System.out.println("Return Value = " + result); logger.info("AfterReturning Advice method stopper : " + joinPoint.getSignature().getName()); }
Let’s see the above code. The second attribute returning in the annotation binds the target method’s return value to the parameter result.
public String fullName(String firstName, String lastName) { return String.format("%s %s", firstName, lastName); }
The above target method fullName returns the first and last name together as a string. If we pass “John” as first name and “Doe” as the last name to this method, then @AfterReturning advice will print “Return Value = John Doe” in the console.
bean.fullName("John", "Doe");
Console output:
Return Value = John Doe
The advice has the first parameter of type org.aspectj.lang.JoinPoint and see this article to know more on this parameter type.
In this article, we have learned the Spring Aspect AfterReturning and a simple example to illustrate it.