java / intermediate
Snippet
Encapsulating Cross-Cutting Execution Timers with Custom AOP Aspects
Aspect-Oriented Programming (AOP) encapsulates cross-cutting concerns such as logging, metrics, or auditing outside of the core business logic. An `@Around` advice intercepts method invocations matching the pointcut, controls the target method execution via `joinPoint.proceed()`, and records execution timing without modifying the original controller or service code.
snippet.java
java
1
2
3
4
5
6
7
8
9
10
11
12
13
@Aspect@Componentpublic class PerformanceAspect {@Around("@annotation(org.springframework.web.bind.annotation.GetMapping)")public Object measureExecutionTime(ProceedingJoinPoint joinPoint) throws Throwable {long start = System.nanoTime();Object result = joinPoint.proceed();long durationMs = (System.nanoTime() - start) / 1_000_000;System.out.printf("%s executed in %d ms%n", joinPoint.getSignature().getName(), durationMs);return result;}}
spring
Breakdown
1
@Around("@annotation(org.springframework.web.bind.annotation.GetMapping)")
Specifies a pointcut matching any method annotated with `@GetMapping`, wrapping its execution.
2
Object result = joinPoint.proceed();
Explicitly invokes the underlying target method and captures its return value.