在两个 around 函数之间传递对象 - AOP

Aka*_*ran 5 annotations aspectj spring-mvc auditing spring-aop

我正在对我的控制器、服务和 Dao 层进行审计。我有三个 around 方面函数,分别用于 Controller、Service 和 Dao。我使用自定义注释,如果控制器方法上存在该注释,则会调用 around 方面函数。在注释中,我设置了一个属性,希望将其从 Aspect 类内的 Controller around 函数传递到 Service around 函数。

public @interface Audit{
   String getType();
}
Run Code Online (Sandbox Code Playgroud)

我将从接口设置此 getType 的值。

@Around("execution(* com.abc.controller..*.*(..)) && @annotation(audit)")
public Object controllerAround(ProceedingJoinPoint pjp, Audit audit){
  //read value from getType property of Audit annotation and pass it to service around function
}

@Around("execution(* com.abc.service..*.*(..))")
public Object serviceAround(ProceedingJoinPoint pjp){
  // receive the getType property from Audit annotation and execute business logic
}
Run Code Online (Sandbox Code Playgroud)

如何在两个 around 函数之间传递对象?

Nán*_*ete 4

默认情况下,方面是单例对象。但是,有不同的实例化模型,这在像您这样的用例中可能很有用。使用percflow(pointcut)实例化模型,您可以将注释的值存储在控制器中围绕通知的值,并在服务中围绕建议检索它。以下只是其外观的示例:

@Aspect("percflow(controllerPointcut())")
public class Aspect39653654 {

    private Audit currentAuditValue;

    @Pointcut("execution(* com.abc.controller..*.*(..))")
    private void controllerPointcut() {}

    @Around("controllerPointcut() && @annotation(audit)")
    public Object controllerAround(ProceedingJoinPoint pjp, Audit audit) throws Throwable {
        Audit previousAuditValue = this.currentAuditValue;
        this.currentAuditValue = audit;
        try {
            return pjp.proceed();
        } finally {
            this.currentAuditValue = previousAuditValue;
        }
    }

    @Around("execution(* com.abc.service..*.*(..))")
    public Object serviceAround(ProceedingJoinPoint pjp) throws Throwable {
        System.out.println("current audit value=" + currentAuditValue);
        return pjp.proceed();
    }

}
Run Code Online (Sandbox Code Playgroud)