2013-07-01 8 views
5

Chcę utworzyć niestandardową adnotację do logowania w moim projekcie Grails.AOP z Grails

Mój kod:

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

Interceptor:

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

Wiosna config:

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

auditLogInterceptor(AuditLogInterceptor) {} 

Rezultat:

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

Chciałbym zobaczyć również ostrzeżenie adnotacji dla metody 2. czego mi brakuje?

Odpowiedz

8

Dzieje się tak, ponieważ metoda wywołuje wewnętrzny w klasie służenia sobie są nie odbywa się na proxy instancji klasy service. Jeśli pobierzesz komponent bean usługi z kontekstu aplikacji i spróbujesz zadzwonić pod numer method2(), powinieneś zobaczyć aspect słuchanie advice.

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

Niezły wgląd! Myślę, że byłoby wspaniale, gdyby Grails zapewniał magię delegowania wywołań metod w tej samej klasie usług do klasy proxy. –