After Returning Advice

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

Controller Class

PaymentApi.java

Run the application and trigger the API

Output

Scenario 2: Logging method response using pointcut expression

Create Aspect class

LoggingAspect.java

Note that pointcut expression matches any class and any method defined under org.example.controller package

Create controller class

DataApi.java

Run the application, trigger the API and verify the logs

Output

Note: The code snippet given in this page is just for understanding and does not contain complete code. (For e.g. missing service class code snippet)

Last updated