2013-07-01 39 views
5

我想在我的Grails項目創建一個自定義日誌註釋。AOP使用Grails

我的代碼:

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

Spring配置:

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提供了一些神奇的功能來委託調用相同服務類中的方法到代理類。 –