1
class User {   
    static constraints = {  
       password(unique:true, length:5..15, validator:{val, obj -> 
          if(val?.equalsIgnoreCase(obj.firstName)) { 
              return false  
          }  
       } 
    } 
}

我发现这种 groovy 语法真的很令人困惑。我花了几天时间尝试学习 grails/groovy。我知道它的作用,但我并不真正理解它。

有人可以解释这是如何工作的吗?

什么是约束?它是一个闭包,密码被作为一个函数调用吗?它是如何被调用的?

那么验证器是什么样的语法呢?

就像我说的我可以看到它的作用,我只是不明白它是如何做到的。

4

2 回答 2

2

前言- 某些部分需要基本的 Groovy 使用知识。

//Domain Class
class User {
    //A property of the domain class 
    //corresponding to a column in the table User.
    String password

    //Domain classes and Command objects are treated specially in Grails
    //where they have the flexibility of validating the properties 
    //based on the constraints levied on them.
    //Similar functionality can be achieved by a POGO class
    //if it uses @Validateable transformation at the class level.   
    static constraints = {  
       //Constraints is a closure where validation of domain class
       //properties are set which can be validated against when the domain class
       //is saved or validate() is called explicitly.
       //This is driven by AbstractConstraint and Constraint java class 
       //from grails-core

       //Constraint on password field is set below.
       //Here password is not treated as a method call
       //but used to set the parameter name in the constraint class on which
       //validation will be applied against. Refer AbstractConstraint 
       //for the same.
       password(unique:true, size:5..15, validator:{val, obj -> 
          //Each of the key in the above map represents a constraint class 
          //by itself
          //For example: size > SizeConstraint; validator > ValidatorConstraint
          if(val?.equalsIgnoreCase(obj.firstName)) { 
              return false  
          }  
       } 
    } 
}

上面提到的是约束如何工作的基础知识。如果您需要了解更多详细信息,那么如果您对它的使用有任何进一步的疑问,您肯定需要访问以下一些资源:

显然,如果您陷入与约束或更多约束相关的任何实现中,那么 SO 是提问的好地方。随意使用这个社区来帮助您克服有问题的编程情况。

于 2013-08-25T02:22:52.397 回答
0

我有同样的问题,也找不到 Groovy 书籍/文档中解释的语法。然后我谷歌并找到这个博客:http ://www.artima.com/weblogs/viewpost.jsp?thread=291467 ,它回答了我的问题。

于 2014-09-01T03:18:53.897 回答