我正在将 spring aop 与 groovy 结合使用,并且有一个监视方面,应该记录每个方法的执行时间。问题是 groovy 调用与 java 调用不同,因此以下代码始终打印“getMetaClass()”作为方法名称。
@Before("execution(* mypackage.MyService.*(..))")
void beforeMethod(JoinPoint joinPoint) {
logger.info(joinPoint.signature.name + " called")
}
我看到有两种方法可以解决这个问题:
- 从 groovy 调用中查找实际方法
- 使用其他方式获取被调用的方法(而不是注入(inject) jointPoint 参数)
有什么想法吗?
最佳答案
对于选项 1:
尝试将 !getMetaClass()
Pointcut
添加到您的 @Aspect
类,如下所示:
@Pointcut("!execution(* mypackage.MyService.*.getMetaClass(..))")
public void noMetaClassMethods() {}
以及将原始执行匹配器变成切入点
:
@Pointcut("execution(* mypackage.MyService.*(..))")
public void myServices() {}
然后将这两个组合在您的 @Before
中,如下所示:
@Before("myServices() && noMetaClassMethods()")
void beforeMethod(JoinPoint joinPoint) {
logger.info(joinPoint.signature.name + " called")
}
它应该会给你你正在寻找的东西。
对于选项 2:您可以将名称属性添加到目标方法的注释中:
@Timed(name="methodIWantToTime")
def methodIWantTime(..)
然后只需将注释作为参数包含在 Aspect
类中:
@Around(value="@annotation(timed)")
def timeMethod(ProceedingJoinPoint proceedingJointPoint, Timed timed) {
println timed.name()
proceedingJointPoint.proceed()
}
然后把它从上面剥下来。
关于Spring AOP 与 groovy : get called method,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28474278/