带有 Grails 的 AOP [英] AOP with Grails

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

问题描述

我想在我的 Grails 项目中创建自定义日志注释.

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

我的代码:

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

弹簧配置:

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 的注解.我错过了什么?

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

推荐答案

出现这种情况是因为服务类中对 self 的内部方法调用没有 服务的代理实例上完成 类.如果您从应用程序上下文中获取服务 bean 并尝试调用 method2(),您应该看到 aspect 正在监听 advice.>

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天全站免登陆