Spring AOP 与 groovy : get called method

标签 spring groovy aop spring-aop

我正在将 spring aop 与 groovy 结合使用,并且有一个监视方面,应该记录每个方法的执行时间。问题是 groovy 调用与 java 调用不同,因此以下代码始终打印“getMetaClass()”作为方法名称。

@Before("execution(* mypackage.MyService.*(..))")
void beforeMethod(JoinPoint joinPoint) {
    logger.info(joinPoint.signature.name + " called")
}

我看到有两种方法可以解决这个问题:

  1. 从 groovy 调用中查找实际方法
  2. 使用其他方式获取被调用的方法(而不是注入(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/

相关文章:

java - 带有 Spring 的slf4中的java.lang.NoClassDefFoundError

java - 如何使用 Spring REST 分块发送大文件(REST 客户端)

groovy - 使用动态对象组配置 gradle 插件扩展的正确方法

grails - Grails-条件构建器-createCriteria

java - 从 groovy 类中的应用程序上下文获取 spring bean

javascript - 无法在选择中选择多个值

c# - 用于记录方法调用和异常的 WCF 服务属性

java - 为什么这个 Spring Aspect 没有按方法参数打印?

c# - 使用属性向方法添加参数

java - 在 Spring Boot 应用程序中使用 Rackspace 时,Apache jclouds java.lang.NoSuchMethodError