Grails中的通用方法拦截(特别是控制器) [英] Generic method interception in grails (specifically Controllers)

查看:122
本文介绍了Grails中的通用方法拦截(特别是控制器)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在grails中创建一个通用函数,它允许我指定一个类和函数名,并根据该条件拦截任何函数调用:

  getSomeClass()。metaClass.invokeMethod = {String methodName,args  - > 
MetaMethod someAction = getSomeClass()。metaClass.getMetaMethod(methodName,args)
def result = someAction.invoke(delegate,args)$ b $ if(methodName == getSomeMethodName())
截取(args,result)
返回结果
}

POGO和域类,但似乎不适用于控制器类。尽管我完全意识到Grails中有控制器拦截器和过滤器,但这些并不真正集中我想要实现的内容,并且试图为某些集中行为创建一个简单的泛型函数。

关于为什么在控制器上无法使用的任何指导将不胜感激,谢谢

解决方案

方法可用于通过Groovy元类机制进行的方法调用,但在Grails 2中,这不适用于控制器操作 - 它们使用普通Java反射调用( java.lang.reflect.Method .invoke ),因此您的自定义 invokeMethod 被绕过。



如果你想一个AOP机制可用于来自Java和Groovy的调用,您可能不得不使用AspectJ加载时编织等方式。 Spring的基于代理的AOP可以工作,但Grails 2控制器系统依赖于具有特定的 @Action 注解(在编译时通过AST转换添加)的操作方法,以及我不知道Spring AOP代理是否保留了生成的代理方法上的目标类的方法注释。


I'm trying to create a generic function in grails that will allow me to specify a class and function name, and intercept any function calls based on that criteria:

getSomeClass().metaClass.invokeMethod = { String methodName, args ->
    MetaMethod someAction =  getSomeClass().metaClass.getMetaMethod(methodName, args)
    def result = someAction.invoke(delegate, args)
    if (methodName==getSomeMethodName())
        intercept(args, result)
    return result
}

This works for POGO, and domain classes, but does not seem to work for controller classes. While I'm fully aware there are Controller interceptors and filters available in Grails, these don't really centralise what I'm trying to achieve, and was trying to create a simple generic function for some centralised behaviour

Any guidance on why this doesn't work on Controllers would be appreciated, thanks

解决方案

Your approach will work for method calls that are made through the Groovy metaclass mechanism, but in Grails 2 this doesn't apply to controller actions - they're called using normal Java reflection (java.lang.reflect.Method.invoke), and therefore your custom invokeMethod is bypassed.

If you want an AOP mechanism that'll work for calls from Java as well as from Groovy you'll probably have to use something like AspectJ load-time weaving. Spring's proxy-based AOP may work but the Grails 2 controller system relies on the action methods having a particular @Action annotation (which is added at compile time by an AST transformation) and I don't know whether Spring AOP proxies preserve method annotations from the target class on the generated proxy methods.

这篇关于Grails中的通用方法拦截(特别是控制器)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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