简体   繁体   中英

Annotated method is not intercepted by Around in AspectJ

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

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 ...).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM