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

Pass object between two Around functions - AOP

我正在为我的控制器、服务和 Dao 层做审计。我分别为 Controller、Service 和 Dao 设置了三个 Around 切面函数。我使用自定义注释,如果它出现在 Controller 方法上,将调用 Around 方面函数。在注释中,我设置了一个 属性,我希望将其从 Controller Around 函数传递到 Aspect class.

内的 Service around 函数
public @interface Audit{
   String getType();
}

我将从接口设置此 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
}

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

默认情况下,方面是单例对象。但是,有不同的实例化模型,它们在像您这样的用例中可能很有用。使用 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();
    }

}