Spring AOP参数

avwztpqn  于 2023-03-16  发布在  Spring
关注(0)|答案(1)|浏览(153)

我在使用Spring AOP时遇到了一个问题。我想在一个切入点中获得Student对象。但是我的JoinPoints可以以任何优先级拥有这个对象。
看看下面的代码片段,我创建了两个不同的连接点和切入点:

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;
        }
    }
}

上面的代码只适用于第一个连接点,所以问题是如何创建一个切入点,它将在输入参数中的学生的任何情况下执行。
我不能使用下面的代码,它抛出runtimeException:
@Before("args(..,com.hadi.student.Student,..)")
我让代码更容易理解,实际上我的点割比这个要大得多。所以请用args的方式回答。

mzaanser

mzaanser1#

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

你的例子稍微简单一点,因为你只想提取一个参数而不是它的注解,所以沿着另外两个答案的思路,你可以使用如下的切入点:

@Before("execution(* *(.., com.hadi.student.Student, ..))")

然后通过迭代thisJoinPoint.getArgs()并检查正确的参数类型来提取通知中的参数,这比直接通过args()将方法参数绑定到通知参数要慢得多,也难看得多。但是对于任意位置的参数,您只能选择使用它,因为args(.., Student, ..)将产生一个“模糊参数绑定”错误。这是因为AspectJ和SpringAOP都不能决定如果方法中有多个Student参数应该发生什么,他们应该选择哪一个?
下面是AspectJ中的一个MCVE(不需要Spring,但工作方式相同):

帮助程序类和驱动程序应用程序:

x一个一个一个一个x一个一个二个x

外观:

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]

相关问题