【问题标题】:grails domain constraints is not a map at runtime like docs suggestgrails域约束不是像文档建议的那样运行时的地图
【发布时间】:2026-01-25 20:35:02
【问题描述】:

文档说,根据版本,访问 Domain.constraints 或 Domain.constrainedProperties 应该给出一个键值映射。

https://grails.github.io/grails2-doc/2.5.4/ref/Domain%20Classes/constraints.html

在运行时,静态约束属性是一个 Map,因此 Map 中的键是属性名称,与键关联的值是 ConstrainedProperty 的实例:

但是,使用 2.5+,在运行时访问约束属性不会提供映射,而是提供闭包,并且我无法访问 ConstrainedProperty 实例。

我也尝试使用 grails 类工具来访问静态属性

GrailsClassUtils.getStaticFieldValue(Domain,"constraints")//this is still a closure

GrailsClassUtils.getStaticFieldValue(Domain,"constrainedProperties")//null, this property doesn't exist below version 3.0

【问题讨论】:

    标签: grails


    【解决方案1】:

    像文档中的示例一样,属性访问对我不起作用

    Domain.constraints //returns closure
    

    但使用 getter 方法可以

    Domain.getConstraints() //returns the map 
    

    【讨论】:

      【解决方案2】:

      https://github.com/jeffbrown/constraintsmapdemo查看项目。

      https://github.com/jeffbrown/constraintsmapdemo/blob/master/grails-app/domain/demo/Widget.groovy:

      package demo
      
      class Widget {
          int width
          int height
          static constraints = {
              width range: 1..100
              height range: 1..50
          }
      }
      

      https://github.com/jeffbrown/constraintsmapdemo/blob/master/test/unit/demo/WidgetSpec.groovy 的测试通过:

      package demo
      
      import grails.test.mixin.TestFor
      import spock.lang.Specification
      
      @TestFor(Widget)
      class WidgetSpec extends Specification {
      
          void "test accessing the constraints property"() {
              when:
              def propValue = Widget.constraints
      
              then:
              propValue instanceof Map
              propValue.containsKey 'width'
              propValue.containsKey 'height'
          }
      }
      

      如果您不使用静态编译,Widget.constraints 将评估为Map。如果您使用静态编译,Widget.getConstraints() 将返回 MapWidget.constraints 将评估为闭包。

      【讨论】:

        最近更新 更多