Spring AOP切入点(如果条件)

我遇到切入点的问题,为此,当log.isDebugEnabled为true时,我试图启用@Around,我正在尝试以下代码:

@Pointcut("within(org.apache.commons.logging.impl.Log4JLogger..*)")
    public boolean isDebugEnabled() {
        return log.isDebugEnabled();
    }

出于测试目的,我配置了两个方面

@AfterThrowing(value = "!isDebugEnabled()",throwing = "exception")

@Around(value = "isDebugEnabled()")

但是,每当我尝试执行代码时,总是到@AfterThrowing,而且我不清楚我在做什么错!

我在Spring MVC 4.3上使用AspectJWeaver 1.8.9!

这是一个模拟问题的示例类:

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.util.StopWatch;

@Component
@Aspect
public class SampleAspect {

    private static final Log log = LogFactory.getLog(SampleAspect.class);

    @Pointcut("within(org.apache.commons.logging.impl.Log4JLogger..*)")
    public boolean isDebugEnabled() {
        return log.isDebugEnabled();
    }

    @AfterThrowing(value = " !isDebugEnabled()",throwing = "exception")
    public void getcalledOnException(JoinPoint joinPoint,Exception exception) {

        log.error("Method " + joinPoint.getSignature() + " Throws the exception " + exception.getStackTrace());
    }

    //Never execute around method even when log.isDebugEnabled() = true
    @Around(value = "isDebugEnabled()")
    public Object aroundTest(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {

        StopWatch stopWatch = new StopWatch();
        stopWatch.start();

        final Object proceed;
        try {
            proceed = proceedingJoinPoint.proceed();
        } catch (Exception e) {
            throw e;
        }
        stopWatch.stop();
        log.debug("It took " + stopWatch.getTotalTimeSeconds() + " seconds to be proceed");

        return proceed;
    }
}

修改, 我尝试使用aspectJ中的if(),但在我的项目中也无法使用。

@Pointcut("call(* *.*(int)) && args(i) && if()")
     public static boolean someCallWithIfTest(int i) {
        return i > 0;
     }

不确定我是否需要添加其他导入,但是我没有设法使其生效。

yubin1006 回答:Spring AOP切入点(如果条件)

来自documentation的点对

  

==春季AOP能力和目标

     

Spring AOP当前仅支持方法执行连接点   (建议在Spring bean上执行方法

     

===声明切入点

     

在AOP的@AspectJ批注样式中,提供了切入点签名   通过常规方法定义,切入点表达式为   使用@Pointcut批注(   切入点签名必须具有无效的返回类型)。

Apache commons类不是由Spring容器管理的。因此以下内容将不被兑现。

@Pointcut("within(org.apache.commons.logging.impl.Log4JLogger..*)")

以下切入点方法无效

public boolean isDebugEnabled() {
        return log.isDebugEnabled();
    }
本文链接:https://www.f2er.com/2933219.html

大家都在问