0 day streak
java / intermediate
Snippet

Implementing Cross-Cutting Concerns with @Aspect

Aspect-Oriented Programming (AOP) allows you to separate cross-cutting concerns like logging, auditing, or security from the main business logic. The @Around advice intercepts method execution to perform logic before and after.

snippet.java
java
1
2
3
4
5
6
7
8
9
10
11
12
@Aspect
@Component
public class PerformanceLoggingAspect {
@Around("execution(* com.example.service.*.*(..))")
public Object logExecutionTime(ProceedingJoinPoint joinPoint) throws Throwable {
long start = System.currentTimeMillis();
Object proceed = joinPoint.proceed();
long executionTime = System.currentTimeMillis() - start;
System.out.println(joinPoint.getSignature() + " executed in " + executionTime + "ms");
return proceed;
}
}
spring
Breakdown
1
@Around("execution(...)")
Defines a pointcut that specifies which methods should be intercepted by this aspect.
2
ProceedingJoinPoint
Allows the aspect to control the flow and actually execute the target method.
3
joinPoint.proceed()
Triggers the execution of the actual method being intercepted.