注解的方法在AspectJ中没有被Around拦截

Annotated method is not intercepted by Around in AspectJ

我正在尝试拦截注释方法的执行以记录执行时间;所以我创建了一个新注释:

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface LogExecutionTime {
}

我在要跟踪的方法上应用注释(方法的 class 未注释,如 @Service 或 @Component;这是一个问题吗?):

@LogExecutionTime
public void execute() throws Exception {
...
}

然后我创建 class 和 @Around 方法:

@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);
}
}

然后我在 pom 中添加 spring-boot-starter-aop 依赖项,并将 @EnableAspectJAutoProxy 添加到主 class(@SpringBootApplication 注释的一个)。 我希望当我调用 execute() 方法时,首先调用 logExecutionTime() 方法(用 @Around 注释的方法)。但事实并非如此。有什么建议么?谢谢

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?):

是的,是的。 Spring 无法在他不知道的 classe 上应用 AOP。我试过你的代码,如果用 @LogExecutionTime 注释的方法在用 @Service (或 @Component...)注释的 class 中,它就可以工作。