This question already has answers here:
Spring AOP not working for method call inside another method

(13个回答)


去年关闭。





我将方面定义如下:

@Component
@Aspect
public class ServiceMethodExecuteTimeAspect {

private Logger logger = LoggerFactory.getLogger(getClass());

@Pointcut("execution(* *.service.*.*(..))")
public void serviceMethod() {

}

@Around("serviceMethod()")
public Object executeTime(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
    Object result;
    MethodSignature signature = (MethodSignature) proceedingJoinPoint.getSignature();
    Method method = signature.getMethod();
    long executeTime;
    long start;
    try {
        start = System.currentTimeMillis();
        result = proceedingJoinPoint.proceed();
        long end = System.currentTimeMillis();
        executeTime = end - start;
        logger.debug("ServiceMethodExecuteTimeAspect class method:{}#{} execute time is:{}", proceedingJoinPoint.getTarget().getClass().getName(), method.getName(), executeTime);
        return result;
    } catch (Throwable throwable) {
        logger.error("ServiceMethodExecuteTimeAspect throw exception", throwable);
        throw throwable;
    }
}
}


我在服务包中有一个Service类,如下所示:

package example.service;
@Service
public class AService{
    public void methodA(){methodB();}
    public void methodB(){}
}


然后,当创建AService实例bean时,获取以下日志:

DEBUG o.s.a.f.CglibAopProxy - Unable to apply any optimizations to advised method: public example.AService.methodB();


然后,弹簧component调用AService.methodA()方法,我想查看AService.methodA()的日志执行时间,并记录AService.methodB()的执行时间,但是我发现它只是AService.methodA()的日志执行时间。

换句话说,当我调用ServiceMethodExecuteTimeAspect时,我的AService.methodB()AService.methodA()上不起作用。

那么,当我调用AService.methodB()方法时,如何使方面在方法AService.methodA()上起作用?

最佳答案

一种方法可以做到这一点,定义另一个Service,然后将方法methodB()移至该方法。

08-18 05:04