首页 > 解决方案 > Spring AOP 切入点 if 条件

问题描述

我正面临切入点的问题,我正在尝试启用@Aroundlog.isDebugEnabled 为 true 时,我正在尝试以下代码:

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

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

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

@Around(value = "isDebugEnabled()")

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

我正在使用 aspectJWeaver 1.8.9 和 Spring MVC 4.3

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

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;
    }
}

编辑,我尝试使用 if() from aspectJ,但它在我的项目中也不起作用。

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

不确定我是否需要添加不同的导入,但我没有设法让它工作。

标签: aopaspectjspring-aop

解决方案


文档中的几点

== Spring AOP 功能和目标

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

=== 声明一个切入点

在AOP的@AspectJ注解风格中,切入点签名由正则方法定义提供,切入点表达式使用@Pointcut注解表示(作为切入点签名的方法必须有一个void返回类型)。

Apache 公共类不由 Spring 容器管理。所以以下将不予兑现。

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

以下切入点方法无效

public boolean isDebugEnabled() {
        return log.isDebugEnabled();
    }

推荐阅读