java - AspectJ:拦截另一个方法内方法的返回结果

标签 java aspectj pointcut pointcuts

我需要帮助就这个特殊情况写一些 Aspectj 建议:

假设我们有这个类:

package org.group;

public class Person {

   public void method1(String id, String number) {
       //some code
       List<String> list = getList(number);
       //some code
   }

   public List<String> getList(String number) {
       return Arrays.asList(number);
   }

}

我想在method1中创建一个Aspectj通知来获取getList的结果。我试试这个:

@Pointcut("execution(* org.group.Person.getList(..))")
public void methodGetList() {

}

@AfterReturning(pointcut = "methodGetList()", returning = "result")
public void afterMethodGetList(JoinPoint joinPoint, List<String> result) {
    System.out.println("I can see the list result: " + result.toString());
}

此建议适用于 getList 方法的所有执行,但我真正想要的是在 method1 调用中获取结果,以获取带有 method1 的 id 的信息,例如如下所示:

<小时/>

'我可以看到 id 为 XXX 的人员的列表结果 [4]'

感谢您的帮助。

最佳答案

您需要将切入点限制为控制流内的执行 - cflow() - 调用方法的参数,并通过 args() 绑定(bind)调用方法的相关参数.

应用:

package org.group;

import java.util.Arrays;
import java.util.List;

public class Person {
  public void method1(String id, String number) {
    // some code
    List<String> list = getList(number);
    // some code
  }

  public List<String> getList(String number) {
    return Arrays.asList(number);
  }

  public static void main(String[] args) {
    // Should not be intercepted
    new Person().getList("22");
    // Should be intercepted
    new Person().method1("John Doe", "11");
  }
}

方面:

package de.scrum_master.aspect;

import java.util.List;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;

@Aspect
public class MyAspect {
  @Pointcut("execution(* org.group.Person.getList(..))")
  public void methodGetList() {}

  @Pointcut("execution(* org.group.Person.method1(..)) && args(id, *)")
  public void methodMethod1(String id) {}

  @AfterReturning(
    pointcut = "methodGetList() && cflow(methodMethod1(id))",
    returning = "result"
  )
  public void afterMethodGetList(JoinPoint joinPoint, String id, List<String> result) {
    System.out.println(
      "I can see the list result " + result +
      " for the person with id " + id
    );
  }
}

控制台日志:

I can see the list result [11] for the person with id John Doe

关于java - AspectJ:拦截另一个方法内方法的返回结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50925870/

相关文章:

java - 多个独立组分注入(inject)

java - JoinPoint 或 ProceedingJoinPoint 的对象为什么可以调用方法?

java - Aspectj:在 aop.xml 中声明时切入点不再起作用(LTW)

spring-boot - Tomcat 8、Spring Boot、@Configurable LoadTimeWeaving 没有 -javaagent?

spring - java.lang.IllegalArgumentException: error at::0 找不到引用的切入点

java - 具有简单类型的 AspectJ 连接点

java - Hibernate JPA 不在类路径上执行 import.sql

java - 在 JDBC 中使用特殊 SQL 关键字更新命令

java - 如何匹配在 AspectJ 中没有特定注解的方法

java - Spring Data JPA - 如何使用组合键插入子实体?