【问题标题】:Dependency Injection In Grails Domain ControllersGrails 域控制器中的依赖注入
【发布时间】:2009-08-25 01:37:20
【问题描述】:

我正在尝试创建一个自定义约束。我已将逻辑放入服务中:

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

【问题讨论】:

    标签: grails grails-validation


    【解决方案1】:

    约束闭包是静态的,因此它看不到实例字段“regExpManagerService”。但是您已经验证了对象,因此您可以从中访问它:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-02-01
      • 1970-01-01
      • 2015-12-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-26
      • 2018-10-21
      相关资源
      最近更新 更多