如何使方面在方法AService.methodB()上起作用?

时间:2019-05-10 08:41:58

标签: java aop spring-aop

我将方面定义如下:

@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()上起作用?

1 个答案:

答案 0 :(得分:0)

一种方法可以做到,定义另一个服务,然后将方法methodB()移到其中。