【问题标题】:Intercepting or renaming a method call in Grails / Groovy在 Grails / Groovy 中拦截或重命名方法调用
【发布时间】:2010-03-04 12:48:21
【问题描述】:

我正在尝试拦截 Grails 应用程序中的方法调用(域类的 afterInsert())。在我的插件的 doWithDynamicMethods 关闭中,我有:

for (dc in application.domainClasses) {
    // What I'm basically doing is renaming method A to B
    // and creating a new method A with its own business logic
    // and a call to B() at the end

    def domainClass = dc.getClazz()
    def oldAfterInsert = domainClass.metaClass.afterInsert
    domainClass.metaClass."afterInsert_old" = oldAfterInsert

    dc.metaClass.afterInsert = {
        // New afterInsert() logic here

        // Call the old after insert
        delegate.afterInsert_old()
    }

}

然后我得到这个错误:

No signature of method: static com.example.afterInsert_old() is applicable for argument types: () values: []

我也尝试使用 dc.metaClass."afterInsert_old".invoke(delegate, new Object[0]) 调用它,但后来我得到:

Caused by: groovy.lang.MissingMethodException: No signature of method: groovy.lang.ExpandoMetaClass$ExpandoMetaProperty.invoke() is applicable for argument types: (com.example.DomainName, [Ljava.lang.Object;) values: [com.example.DomainName : 115, []]

我做错了什么?如何调用不带参数的方法?

我了解 AOP,并且还看到了 Grails Audit Logging 插件作为示例。但是,据我所知,它的作用是添加新的用户创建的方法,这些方法会在正确的时间触发。我想自动注入我的代码,这样用户就不必担心任何事情,我不想破坏他原来的 afterInsert() (或任何方法)实现。

另外,我想对暴露的服务方法做同样的事情,以便为它们注入安全性。但是,从我读到的内容来看,由于 BeanWrapper 并且服务总是重新加载,因此它不起作用。有人可以向我更好地解释一下吗?

提前致谢。

【问题讨论】:

    标签: grails groovy interceptor


    【解决方案1】:

    我认为您不需要重命名旧方法。你可以像this example:

    for (dc in application.domainClasses) {
        // What I'm basically doing is renaming method A to B
        // and creating a new method A with its own business logic
        // and a call to B() at the end
        def domainClass = dc.getClazz()
        def savedAfterInsert = domainClass.metaClass.getMetaMethod('afterInsert', [] as Class[])
        domainClass.metaClass.afterInsert = {
            // New afterInsert() logic here
    
            // Call the old after insert
            savedAfterInsert.invoke(delegate)
        }
    
    }
    

    只要确保 getMetaMethod 返回正确的方法即可。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-05-23
      • 1970-01-01
      • 2012-08-29
      • 2018-06-08
      • 2021-09-16
      • 2014-10-11
      • 2011-02-11
      相关资源
      最近更新 更多