【问题标题】:Annotated method is not intercepted by Around in AspectJAspectJ中的Around不会拦截带注释的方法
【发布时间】:2020-10-09 23:03:05
【问题描述】:

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

@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 注释的那个)。但事实并非如此。有什么建议么?谢谢

【问题讨论】:

    标签: java spring-boot aspectj


    【解决方案1】:

    我在要跟踪的方法上应用注解(方法的类没有注解,如@Service@Component;这是个问题吗?):

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

    【讨论】:

    • 你必须将这个类注解为服务,并在你调用注解方法的类中自动装配它
    • @S-Wing 是的,就是这样,然后 Spring 可以做到这一点;)
    猜你喜欢
    • 1970-01-01
    • 2019-10-20
    • 1970-01-01
    • 2018-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多