【问题标题】:Common beforeUpdate method for Grails domainGrails 域的常用 beforeUpdate 方法
【发布时间】:2020-03-05 02:37:37
【问题描述】:

我正在尝试通过写BootStrap.groovy 来使用常见的beforeUpdate 方法。

def init = { servletContext ->
         for (domainClass in grailsApplication.domainClasses) {
            if(domainClass.clazz.simpleName == domainName){
                domainClass.metaClass.beforeUpdate = {
                    println  "i am here "
                    def dirtyPropertyNames = this.getDirtyPropertyNames()
                    println(dirtyPropertyNames)
                    if(dirtyPropertyNames != null && dirtyPropertyNames.size() > 0) {

                        for (dirtyPropertyName in dirtyPropertyNames) {
                            def oldValue = (this.getPersistentValue((dirtyPropertyName)))
                            def newValue = (this."${dirtyPropertyName}")
                        }
                    }
                }
            }
        }
    }

但我不能使用this.getdirtyPropertyNames(),因为它会报错。

groovy.lang.MissingMethodException:没有方法签名:

如果它在域本身中,this.getDirtyPropertyNames() 可以正常工作。 我也尝试过使用domainClass.getDirtyPropertyNames(),但仍然报错。

我正在使用 Grails 4。

【问题讨论】:

    标签: grails grails-4


    【解决方案1】:

    我不确定你是否在问如何完成你想要的,或者为什么你会得到你得到的错误。

    如果你想知道如何完成你想要的,我会使用事件监听器而不是元编程方法。有很多例子,https://github.com/jeffbrown/gorm-events-demo/blob/261f25652e5fead8563ed83f7903e52dfb37fb40/src/main/groovy/gorm/events/demo/listener/AuditListener.groovy#L22-L26 就是其中之一。

    如果您问为什么会收到错误,原因是 this 引用了 BootStrap 的实例,而不是您的域类的实例。如果您真的想使用动态元编程方法(您不应该),那么您可以通过引用 delegate 而不是 this 来解决问题的特定部分。

    希望对你有帮助。

    【讨论】:

    • 谢谢您..with 'delegate' 解决了这个问题,但是您的建议将尝试使用 Listener
    • 太棒了。祝你好运!
    猜你喜欢
    • 2012-03-06
    • 2014-08-03
    • 2015-03-13
    • 2011-08-21
    • 1970-01-01
    • 2017-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多