【问题标题】:GrailsApplication in Domain Class领域类中的 GrailsApplication
【发布时间】:2021-08-20 09:48:05
【问题描述】:

我想写以下内容:

import grails.core.GrailsApplication

class MyDomainClass{
    GrailsApplication grailsApplication
    String otherName
    
    String getName(){
        String prop =  grailsApplication.config.getProperty('my.property.from.application.yml')
        return prop + otherName
    }
    static mapping = {
        autowire true
    }
}

但是,如果我在域类中有 grailsApplication,则 grails 命令grails run-app 不会启动网络服务器并永远等待。它输出以下警告,但没有错误:

> IDLE
WARNING: An illegal reflective access operation has occurred
WARNING: Illegal reflective access by org.codehaus.groovy.reflection.CachedClass (file:/Users/martin/.gradle/caches/modules-2/files-2.1/org.codehaus.groovy/groovy/2.5.14/f0a005fb21e7bd9b7ebf04cd2ecda0fc8f3be59d/groovy-2.5.14.jar) to method java.util.AbstractMap.clone()
WARNING: Please consider reporting this to the maintainers of org.codehaus.groovy.reflection.CachedClass
WARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operations
WARNING: All illegal access operations will be denied in a future release
WARNING: An illegal reflective access operation has occurred
WARNING: Illegal reflective access by org.codehaus.groovy.reflection.CachedClass (file:/Users/martin/.gradle/caches/modules-2/files-2.1/org.codehaus.groovy/groovy/2.5.14/f0a005fb21e7bd9b7ebf04cd2ecda0fc8f3be59d/groovy-2.5.14.jar) to method java.lang.Object.finalize()
WARNING: Please consider reporting this to the maintainers of org.codehaus.groovy.reflection.CachedClass

这是一种不好的做法还是错误?我该如何解决这个问题?在我看来,最明显的选择是调用服务。

我正在使用以下 Grails 版本:

| Grails Version: 4.0.11
| JVM Version: 11.0.11

【问题讨论】:

  • grailsApplication 中的 A 在变量定义中大写,但在使用时不大写。
  • 我不知道将 grailsApplication 放在域类中是否“错误”,但这肯定是不必要的。您可以在任何地方使用grails.util.Holders.config 来访问配置,这将比注入 grailsApplication 更简单、更干净。
  • 声明 grailsApplication 瞬态。此外,您似乎想在 static transients 块中定义 name 属性

标签: grails groovy


【解决方案1】:

添加 WebAttribute Trait,然后您将获得 grailsApplication。

9.1.1 WebAttributes Trait Example

WebAttributes 是框架提供的特征之一。任何 Groovy 类可以实现这个 trait 来继承所有的属性 以及 trait 提供的行为。

src/main/groovy/demo/Helper.groovy:

package demo

import grails.web.api.WebAttributes

class Helper implements WebAttributes {

    List<String> getControllerNames() {
        // There is no need to pass grailsApplication as an argument
        // or otherwise inject the grailsApplication property.  The
        // WebAttributes trait provides access to grailsApplication.
        grailsApplication.getArtefacts('Controller')*.name
    }
}

【讨论】:

  • 这绝对是在任何其他类型的类中执行此操作的方法,但对于域类却失败了。实际上,我很惊讶,如果我们以这种方式访问​​grailsApplication,它不会启动网络服务器。我决定通过@Daniel 提出的grails.util.Holders.config 访问配置。
  • 感谢它在 Grails 3.2.12 中对我有用,但 Holders 似乎同样好,甚至可能是最好的解决方案。
猜你喜欢
  • 2011-12-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多