Reputation: 579
I'm trying to intercept the execution of an annotated method to log the execution time; so I create a new annotation:
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface LogExecutionTime {
}
I apply the annotation over the method that I want to trace (the class of the method is not annotated, like @Service or @Component; is this a problem?):
@LogExecutionTime
public void execute() throws Exception {
...
}
Then I create the class and the @Around method:
@Aspect
@Component
public class PerformanceAnnotation {
@Around("@annotation(LogExecutionTime)")
public void logExecutionTime(ProceedingJoinPoint joinPoint) throws Throwable {
Logger logger = getClassLogger(joinPoint);
logger.info("Started method " + joinPoint.getSignature().getName() + " of class " + joinPoint.getTarget().getClass());
long start = System.currentTimeMillis();
joinPoint.proceed();
long executionTime = System.currentTimeMillis() - start;
logger.info("Execution time (millis): " + executionTime);
}
}
And I add the spring-boot-starter-aop dependency in the pom, and the @EnableAspectJAutoProxy to the main class (the @SpringBootApplication annotated one ). I expect that when I call the execute() method, the method logExecutionTime() ( the one annotated with @Around) is called first. But it doesn't. Any suggestions? Thanks
Upvotes: 1
Views: 956
Reputation: 264
I apply the annotation over the method that I want to trace (the class of the method is not annotated, like
@Service
or@Component
; is this a problem?):
Yes, it is. Spring cannot apply AOP on classe that he's not aware of. I tried your code and it works if the method annoted with @LogExecutionTime
is in a class annoted with @Service
(or @Component
...).
Upvotes: 1