2016-09-23 11 views
4

私はController、Service、およびDao層の監査を行っています。私はコントローラ、サービス、Daoの3つのAroundアスペクト機能を持っています。私はコントローラメソッド上に存在する場合、Aroundアスペクト関数を呼び出すカスタムアノテーションを使用します。注釈の中で私は、Controller Around関数からAspectクラス内のService around関数に渡したいプロパティを設定しました。2つの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 
} 

2つのAround関数間でオブジェクトを渡すにはどうすればよいですか?

答えて

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

} 
+0

と[ワームホールパターン]の変形を記述する(http://stackoverflow.com/a/12130175/1082681)。 'percflow()'インスタンス化ではなく、 'cflow()'ポイントカットを使ってシングルトンアスペクトを実装する方法を知りたい場合は、リンクを参照してください。そのようなパターンは同じですが、アスペクトインスタンスが少なくて済みます。 – kriegaex

+0

@Nandor Elod Fekete - ありがとう、私は新しいことを学び、あなたの提案は魅力的に機能しました。 –

関連する問題