2009-08-25 3 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

Это сделало его. Теперь я просто должен выяснить, как получить локаль ... –

Смежные вопросы