2013-07-01 7 views
5

Grailsプロジェクトでカスタムロギングアノテーションを作成したいとします。Grailsを使用したAOP

マイコード:

class MyService{ 
    @AuditLog 
    def method1() { 
     println "method1 called" 
     method2() 
    } 
    @AuditLog 
    def method2() { 
     println "method2 called" 
    } 
} 

インターセプター:

class AuditLogInterceptor implements MethodInterceptor { 
    @Override 
    Object invoke(MethodInvocation methodInvocation) throws Throwable { 
     println "${methodInvocation.method}" 
     return methodInvocation.proceed(); 
    } 
} 

春:configと

aop { 
    config("proxy-target-class": true) { 
     pointcut(id: "auditLogInterceptorPointcut", expression: "@annotation(xxx.log.AuditLog)") 
     advisor('pointcut-ref': "auditLogInterceptorPointcut", 'advice-ref': "auditLogInterceptor") 
    } 
} 

auditLogInterceptor(AuditLogInterceptor) {} 

結果:

public java.lang.Object xxx.MyService.method1() 
method1 called 
method2 called 

方法2のアノテーションの火災も見たいと思います。私は何が欠けていますか?

答えて

8

内部メソッドは、serviceクラスのプロキシされたインスタンス上で行われていない自己へのサービス・クラスで呼び出すためです。アプリケーションコンテキストからサービスBeanを取得してmethod2()にコールしようとすると、aspectadviceを待ち受けるはずです。

class MyService{ 
    static transactional = false 
    def grailsApplication 

    @AuditLog 
    def method1() { 
     println "method1 called" 
     grailsApplication.mainContext.myService.method2() 
     //method2() 
    } 
    @AuditLog 
    def method2() { 
     println "method2 called" 
    } 
} 
+0

ニースの洞察! Grailsが同じサービスクラスのメソッドへの呼び出しをプロキシクラスに委譲するいくつかの魔法を提供するなら、それは素晴らしいことだと思います。 –

関連する問題