Skip to content

Instantly share code, notes, and snippets.

@susimsek
Last active September 6, 2024 17:21
Show Gist options
  • Save susimsek/94e9be3886a447447f22d9aea6f6371e to your computer and use it in GitHub Desktop.
Save susimsek/94e9be3886a447447f22d9aea6f6371e to your computer and use it in GitHub Desktop.
Spring Boot Measure Execution Time using Spring AOP
@Aspect
@Component
@Slf4j
@ConditionalOnExpression("${aspect.enabled:true}")
public class ExecutionTimeAdvice {
@Around("@annotation(TrackExecutionTime)")
public Object executionTime(ProceedingJoinPoint point) throws Throwable {
long startTime = System.currentTimeMillis();
Object object = point.proceed();
long endtime = System.currentTimeMillis();
log.info("Class Name: "+ point.getSignature().getDeclaringTypeName() +". Method Name: "+ point.getSignature().getName() + ". Time taken for Execution is : " + (endtime-startTime) +"ms");
return object;
}
}
@Service
public class MessageService {
@TrackExecutionTime
@Override
public List<AlbumEntity> getMessage() {
return "Hello message";
}
}
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface TrackExecutionTime {
}
@javiruizidneo
Copy link

Thanks a lot

@tsv-leinfelden-turnen
Copy link

I have a method marked with @PostConstruct. Adding @TrackExecutionTime does not work here. Any idea why, and what could be done to solve this?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment