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
packageorg.example.logging;importjava.lang.annotation.ElementType;importjava.lang.annotation.Retention;importjava.lang.annotation.RetentionPolicy;importjava.lang.annotation.Target;@Target(ElementType.METHOD) // Annotation will be applicable on methods only@Retention(RetentionPolicy.RUNTIME) // Annotation will be available to the JVM at runtimepublic @interfaceLogExecutionTime {}
Create Aspect class
LoggingAspect.java
packageorg.example.logging;importlombok.SneakyThrows;importlombok.extern.slf4j.Slf4j;importorg.aspectj.lang.ProceedingJoinPoint;importorg.aspectj.lang.annotation.Around;importorg.aspectj.lang.annotation.Aspect;importorg.springframework.stereotype.Component;importjava.time.OffsetDateTime;@Slf4j@Aspect@ComponentpublicclassLoggingAspect { @SneakyThrows @Around("@annotation(LogExecutionTime)")publicObjectlogExecutionTime(ProceedingJoinPoint joinPoint) {log.info("Started - {}",OffsetDateTime.now());// Perform custom logic before method execution// Proceed with the method executionfinalObject proceed =joinPoint.proceed();// Perform custom logic after method executionlog.info("Completed - {}",OffsetDateTime.now());return proceed; }}