Details as well as Examples covering After Returning Advice.
After returning advice is executed after the target method successfully returns a result. It allows to perform additional actions based on the returned result. Some of the use cases are described below.
Logging: It can be used to log method response. This can be helpful for debugging, auditing, or monitoring purposes.
Notification: It it can be used to trigger notification logic such as sending SMS, Email etc. after successful response.
Sample Examples
Scenario 1: Triggering SMS on the successful method invocation
Create custom annotation
SmsOnSuccess.java
package org.example.sms;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.METHOD) // Annotation will be applicable on methods only
@Retention(RetentionPolicy.RUNTIME) // Annotation will be available to the JVM at runtime
public @interface SmsOnSuccess {
}
Create Aspect class
SmsOnSuccessAspect.class
package org.example.sms;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
@Slf4j
@Aspect
@Component
public class SmsOnSuccessAspect {
@AfterReturning("@annotation(SmsOnSuccess)")
public void sendSmsOnSuccess() {
log.info("Sending SMS...");
}
}