java / intermediate
Snippet
Aspect-Oriented Programming (AOP) for Performance Monitoring
AOP allows you to separate cross-cutting concerns like logging or timing from your actual business logic. Using the @Around advice, you can intercept method calls, execute logic before and after, and even modify the return value.
snippet.java
java
1
2
3
4
5
6
7
8
9
10
11
12
@Aspect@Componentpublic class ExecutionTimeAspect {@Around("@annotation(LogExecutionTime)")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("@annotation(LogExecutionTime)")
Defines a Pointcut that targets any method annotated with @LogExecutionTime.
2
joinPoint.proceed()
Executes the actual method being intercepted.
3
joinPoint.getSignature()
Retrieves the information about the method that was called.