当前位置: 首页 > 知识库问答 >
问题:

Spring AOP args

仇炜
2023-03-14
public Student createStudent(String s, Student student) {...}
public Student updateStudent(Student student, String s) {...}

@Before("args(..,com.hadi.student.Student)") 
public void myAdvice(JoinPoint jp) {
    Student student = null;
    for (Object o : jp.getArgs()) {
        if (o instanceof Student) {
            student = (Student) o;
        }
    }
}

上面的代码只适用于第一个JoinPoint。因此,问题是如何创建一个切入点,将执行的任何情况下的学生在输入参数。
我无法使用下面的代码,它引发RuntimeException:
@before(“args(..,com.hadi.student.student,..)”)

我使代码易于理解,实际上我的Poincut比这更大。所以请用args的方式回答。

共有1个答案

东门清夷
2023-03-14

类似的问题我已经回答过好几次了,例如:

  • AspectJ切入点表达式在任意位置匹配参数注释
  • 如何基于带注释的参数编写方面切入点

您的情况稍微简单一点,因为您只想提取参数,而不是它的注释。因此,按照其他两个答案的思路,您可以使用如下的切入点:

@Before("execution(* *(.., com.hadi.student.Student, ..))")
package de.scrum_master.app;

public class Student {
  private String name;

  public Student(String name) {
    this.name = name;
  }

  @Override
  public String toString() {
    return "Student [name=" + name + "]";
  }
}
package de.scrum_master.app;

public class Application {
  public void doSomething() {}

  public Student createStudent(String s, Student student) {
    return student;
  }

  public Student updateStudent(Student student, String s) {
    return student;
  }

  public void marryStudents(Student student1, Student student2) {}

  public static void main(String[] args) {
    Application application = new Application();
    application.doSomething();
    application.createStudent("x", new Student("John Doe"));
    application.updateStudent(new Student("Jane Doe"), "y");
    // What happens if we have multiple Student parameters?
    application.marryStudents(new Student("Jane"), new Student("John"));
  }
}
package de.scrum_master.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;

import de.scrum_master.app.Student;

@Aspect
public class MyAspect {
  @Before("execution(* *(.., de.scrum_master.app.Student, ..))")
  public void interceptMethodsWithStudentArgs(JoinPoint thisJoinPoint) throws Throwable {
    System.out.println(thisJoinPoint);
    for(Object arg : thisJoinPoint.getArgs()) {
      if (!(arg instanceof Student))
        continue;
      Student student = (Student) arg;
      System.out.println("  " + student);
    }
  }
}
execution(Student de.scrum_master.app.Application.createStudent(String, Student))
  Student [name=John Doe]
execution(Student de.scrum_master.app.Application.updateStudent(Student, String))
  Student [name=Jane Doe]
execution(void de.scrum_master.app.Application.marryStudents(Student, Student))
  Student [name=Jane]
  Student [name=John]
 类似资料:

相关问答

相关文章

相关阅读