簡體   English   中英

AspectJ中的Around不會攔截注解的方法

[英]Annotated method is not intercepted by Around in AspectJ

我試圖攔截一個帶注釋的方法的執行來記錄執行時間; 所以我創建了一個新的注釋:

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

我在我想要跟蹤的方法上應用了注釋(方法的類沒有被注釋,比如 @Service 或 @Component;這是一個問題嗎?):

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

然后我創建類和@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 添加到主類(@SpringBootApplication 注釋的一個)。 我希望當我調用 execute() 方法時,首先調用方法 logExecutionTime() (用 @Around 注釋的那個)。 但事實並非如此。 有什么建議? 謝謝

我在要跟蹤的方法上應用注釋(方法的類沒有注釋,如@Service@Component ;這是一個問題嗎?):

是的。 Spring 不能在他不知道的類上應用 AOP。 我試過你的代碼,如果用@LogExecutionTime的方法在用@Service (或@Component ...)注釋的類中,它就可以工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM