2016-09-23 133 views
4

我正在爲我的Controller,Service和Dao層執行審計。對於Controller,Service和Dao,我有三個Around方面的函數。我使用自定義註釋,如果Controller方法存在,將調用Around方面的功能。在註解中,我設置了一個屬性,我希望從Controller Around函數傳遞給Aspect類中的Service around函數。在兩個函數之間傳遞對象Around函數 - AOP

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 
} 

如何在兩個函數之間傳遞一個對象?

回答

4

方面默認情況下是singleton對象。但是,有不同的實例化模型,這些模型在像您這樣的用例中很有用。使用實例化模型,您可以將註釋的值存儲在控制器中,然後在建議中將其檢索到。以下僅爲示例:

@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(); 
    } 

} 
+0

答案正確,並描述了[蟲孔模式](http://stackoverflow.com/a/12130175/1082681)的變體。如果你想知道如何使用'cflow()'切入點而不是'percflow()'實例化來實現與singleton方面相同的功能,請查看鏈接。儘管如此,模式仍然保持不變,您只需要更少的方面實例。 – kriegaex

+0

@Nandor Elod Fekete - 謝謝你,我學到了一件新東西,你的建議就像魅力一樣。 –