与Grails的AOP [英] AOP with Grails

查看:549
本文介绍了与Grails的AOP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我的代码:



<$ p $

我想在我的Grails项目中创建自定义日志记录。
@AuditLog
def method1(){
printlnmethod1 called
method2()
}
@AuditLog
def method2(){
printlnmethod2 called
}
}



拦截器:
$ b $ pre $ 类AuditLogInterceptor实现了MethodInterceptor {
@Override
对象调用(MethodInvocation methodInvocation)throws Throwable {
println$ {methodInvocation.method}
return methodInvocation.proceed();


$ / code $ / pre
$ b $ p

Spring配置:

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

auditLogInterceptor(AuditLogInterceptor){}

结果:

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

我也想看到方法2的注释。我错过了什么?

解决方案

发生这种情况是因为服务类中的内部方法调用为 服务类的代理实例上完成。如果您从应用程序上下文中获取服务bean并尝试调用 method2(),您应该会看到方面正在侦听建议

  class MyService {
static transactional = false
def grailsApplication

@AuditLog
def method1(){
printlnmethod1 called
grailsApplication.mainContext.myService.method2()
// method2()
}
@AuditLog
def method2(){
printlnmethod2 called
}
}


I want to create a custom logging annotation in my Grails project.

My code:

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

Spring config:

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

auditLogInterceptor(AuditLogInterceptor) {}

The result:

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

I would like to see the annotation fire for method 2 as well. What am I missing?

解决方案

This happens because the internal method calls in the service class to self are not done on the proxied instance of the service class. If you fetch the service bean from the application context and try to call method2() you should see the aspect listening to the 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"
    }
}

这篇关于与Grails的AOP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆