Before Advice

Details as well as Examples covering Before Advice.

Before Advice is executed before the advised method execution. It allows to execute custom logic or perform certain actions before the target method is invoked. Some of the use cases are described below.

Logging: Before Advice can be used to log method invocations, providing information such as the method name and parameters. This can be helpful for debugging, auditing, or monitoring purposes.

Security Checks: Before advice can be used to perform security checks before executing sensitive methods. For example, checking if the user has the required permissions or if the request is coming from a trusted source.

Parameter Validation: Before advice can validate method parameters before executing the method. This ensures that the method receives valid input and prevents potential errors or security vulnerabilities.

Caching: Before advice can check if the requested data is already available in the cache before executing expensive database queries. If the data is found in the cache, the method execution can be skipped, improving performance.

Transaction Management: Before advice can be used to start a transaction before executing methods that require database operations.

Sample Examples

Scenario 1: Logging request details using custom annotation

Create custom annotation LogRequest

LogRequest.java

package org.example.logging;

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 LogRequest {
}

Create Aspect class

LoggingAspect.java

Add the annotation on the Controller method.

Run and execute the API and verify the log response.

Postman
Output

Passing argNames in the Before Advice annotation.

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