aop - Spring AOP 切入点 if 条件
问题描述
我正面临切入点的问题,我正在尝试启用@Around
log.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;
}
不确定我是否需要添加不同的导入,但我没有设法让它工作。
解决方案
文档中的几点
== 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();
}
推荐阅读
- render - A 帧渲染 lop 和视图刷新
- java - Groovy Shell 脚本对象未完全执行
- java - 从表 1 中获取用户列表,然后与表 2 中的数据进行比较
- angular - RXJS - 3 个并行的 observables,然后发出值并使用它来调用 3 个串联的 observables
- javascript - 如何访问 jquery 中的 css * 选择器?
- asp.net - 简单电子邮件服务中的 Web API 和电子邮件配置
- mysql - 无法从 cronjob 运行 smbclient 进行远程文件共享
- clickhouse - clickhouse分布式查询实现需要步骤
- java - 模块信息中的 Javadoc 注释
- docker - 使用 docker 镜像在 Mesos 上运行 Spark