注册自定义约束 [英] Register custom constraints

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

问题描述

我正在尝试将Grails 2.3.7项目升级到Grails 3.2.3。在2.3.7中,我使用了自定义约束并使用以下方法将其注册到/conf/Config.groovy:

I'm trying to upgrade Grails 2.3.7 project to Grails 3.2.3. In 2.3.7, I used custom constraints and register them in /conf/Config.groovy using:

org.codehaus.groovy.grails.validation.ConstrainedProperty.registerNewConstraint('description', my.validation.DescriptionConstraint)

然后我可以在域中使用这样的东西:

Then I can use something like this in domain:

static constraints = {
  approvedDate(description: '>= applyDate')
}

然而,在Grails 3.2.3中,当我把上面的命令在/conf/application.groovy中删除org.codehaus.groovy)我得到以下错误:

However, in Grails 3.2.3, When I put above command (and remove org.codehaus.groovy from package name) in /conf/application.groovy I got following error:

Error occurred running Grails CLI: No signature of method: groovy.util.ConfigObject.registerNewConstraint() is applicable for argument types: (groovy.util.ConfigObject, groovy.util.ConfigObject) values: [[:], [DESCRIPTION_CONSTRAINT:[:]]]

我注意到Grails 3中的验证类有所改变。使用Grails-validation中的约束类仍然有同样的错误。

I've notice that validation class is somewhat changed in Grails 3. However using constraint class from Grails-validation still got the same error.

我发现的所有验证插件在Grails 3之前就已经被遗弃了。而且我找不到任何文档在Grails 3.2中注册新约束。

All validation plugins I found were long abandoned before Grails 3. And I can't find any document for register new constraint in Grails 3.2.

推荐答案

调用 ConstrainedProperty.registerNewConstraint in /grails-app/init/BootStrap.groovy工作。 (用Grails 3.2.4测试)

Calling ConstrainedProperty.registerNewConstraint in /grails-app/init/BootStrap.groovy works. (tested with Grails 3.2.4)

class BootStrap {
  def init = { servletContext ->
    grails.validation.ConstrainedProperty.registerNewConstraint('description', my.validation.DescriptionConstraint)
    // The rest of bootstrap code
  }
}

注意。以前,我在/grails-app/init/Application.groovy中从 main()调用它。它适用于运行应用程序。但是,它不适用于集成测试。

Note. Previously, I call it from main() in /grails-app/init/Application.groovy. It works for running application. However, it does not work with integration test.

这篇关于注册自定义约束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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