Details as well as Examples covering Around Advice.
Around advice wraps around the target method invocation. It allows to control the method invocation, including modifying the method arguments, skipping method execution, or replacing the method result. Some of the use cases are described below.
Caching: Helpful in manual cache checking if the requested data is available in the cache before proceeding with the method execution.
Security Checks: Useful in performing authentication and authorization checks before allowing access.
Logging: Can be used in calculating execution time.
Sample Example
Scenario 1: Log method execution time using custom annotation.
Create a custom annotation
LogExecutionTime.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 LogExecutionTime {
}
Create Aspect class
LoggingAspect.java
package org.example.logging;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import java.time.OffsetDateTime;
@Slf4j
@Aspect
@Component
public class LoggingAspect {
@SneakyThrows
@Around("@annotation(LogExecutionTime)")
public Object logExecutionTime(ProceedingJoinPoint joinPoint) {
log.info("Started - {}", OffsetDateTime.now());
// Perform custom logic before method execution
// Proceed with the method execution
final Object proceed = joinPoint.proceed();
// Perform custom logic after method execution
log.info("Completed - {}", OffsetDateTime.now());
return proceed;
}
}