2009-08-25 30 views
2

我试图创建一个自定义约束。我已经把逻辑服务:Grails域控制器中的依赖注入

class RegExpManagerService { 

    boolean transactional = false 
    def messageSource 

    def lookupRegexp(regExpression,Locale locale) { 

     def pattern = messageSource.getMessage(regExpression,null,locale) 
     return pattern 
    } 

    def testRegexp(regExpression,text,Locale locale) { 
     return text ==~ lookupRegexp(regExpression,locale) 
    } 
} 

,并试图在我的域控制器注入它:

class Tag extends IbidemBaseDomain { 

    def regExpManagerService 
    static hasMany=[itemTags:ItemTag] 
    static mapping = { 
     itemTags fetch:"join" 
    } 

    //Long id 
    Date dateCreated 
    Date lastUpdated 
    String tag 
    // Relation 
    Tagtype tagtype 
    // Relation 
    Customer customer 
    // Relation 
    Person updatedByPerson 
    // Relation 
    Person createdByPerson 

    static constraints = { 
     dateCreated(nullable: true) 
     lastUpdated(nullable: true) 
     tag(blank: false,validator: {val,obj -> 
       regExpManagerService.testRegexp(obj.tagtype.regexpression,val,local) 
     }) 
     tagtype(nullable: true) 
     customer(nullable: true) 
     updatedByPerson(nullable: true) 
     createdByPerson(nullable: true) 
    } 
    String toString() { 
     return "${tag}" 
    } 
} 

当约束被执行我得到这个错误:

2009-08-24 18:50:53,562 [http-8080-1] ERROR errors.GrailsExceptionResolver - groovy.lang.MissingPropertyException: No such property: regExpManagerService for class: org.maflt.ibidem.Tag 
org.codehaus.groovy.runtime.InvokerInvocationException: groovy.lang.MissingPropertyException: No such property: regExpManagerService for class: org.maflt.ibidem.Tag 

回答

3

约束闭包是静态的,所以它看不到实例字段'regExpManagerService'。但是,您的对象正在验证中,因此您可以从中进行访问:

tag(blank: false,validator: {val,obj -> 
     obj.regExpManagerService.testRegexp(obj.tagtype.regexpression,val,local) 
    }) 
+0

这样做。现在我只需要弄清楚如何获取语言环境...... – 2009-08-25 04:53:25