【问题标题】:AOP with Grails带有 Grails 的 AOP
【发布时间】:2013-07-01 17:13:36
【问题描述】:

我想在我的 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();
    }
}

弹簧配置:

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 的注释触发。我错过了什么?

【问题讨论】:

    标签: java spring grails groovy aop


    【解决方案1】:

    发生这种情况是因为服务类中对 self 的内部方法调用service 类的代理实例上完成。如果您从应用程序上下文中获取服务 bean 并尝试调用 method2(),您应该会看到 aspect 正在监听 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 提供一些魔法来将同一服务类中的方法调用委托给代理类,那就太好了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-03
    • 1970-01-01
    • 1970-01-01
    • 2020-09-17
    • 2011-12-30
    相关资源
    最近更新 更多