【问题标题】:Pass object between two Around functions - AOP在两个 Around 函数之间传递对象 - AOP
【发布时间】:2016-09-23 06:05:53
【问题描述】:

我正在为我的 Controller、Service 和 Dao 层进行审计。我分别为 Controller、Service 和 Dao 提供了三个环绕方面的功能。我使用了一个自定义注解,如果出现在 Controller 方法上,它将调用一个 Around 方面函数。在注释中,我设置了一个属性,我希望将其从 Controller Around 函数传递给 Aspect 类中的 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 函数之间传递对象?

【问题讨论】:

    标签: spring-mvc annotations aspectj spring-aop auditing


    【解决方案1】:

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

    【讨论】:

    • 答案是正确的并且描述了wormhole pattern 的变体。如果您想知道如何使用cflow() 切入点而不是percflow() 实例化实现单例方面,请查看链接。这样的模式保持不变,但您将拥有更少的方面实例。
    • @Nandor Elod Fekete - 谢谢你,我学到了新东西,你的建议很有魅力。
    猜你喜欢
    • 2015-09-18
    • 1970-01-01
    • 1970-01-01
    • 2019-09-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多