如何从域对象或静态范围获取 Config.groovy 信息?我现在正在使用 ConfigurationHolder.config.*,但它和 ApplicationHolder 已被弃用,所以我想“正确地做”......但 grailsApplication 对象在 DO/静态范围内不可用。
4 回答
Grails 2 替代了已弃用ApplicationHolder
的 ,ConfigurationHolder
等grails.util.Holders
,它提供了相同的功能,但在同一容器中的多个不同 web 应用程序在父类加载器中共享 Grails JAR 的单个副本时,它是安全的(这是旧持有人破产的情况)。
import grails.util.Holders
// ...
static void foo() {
def configOption = Holders.config.myapp.option
}
我将添加grailsApplication
到域类的元类中——这是我正在考虑为 2.0 final 做的事情。现在,把它放进去BootStrap.groovy
,例如
class BootStrap {
def grailsApplication
def init = { servletContext ->
for (dc in grailsApplication.domainClasses) {
dc.clazz.metaClass.getGrailsApplication = { -> grailsApplication }
dc.clazz.metaClass.static.getGrailsApplication = { -> grailsApplication }
}
}
}
然后,您可以通过或仅访问来自grailsApplication.config
和 Spring bean的配置。grailsApplication.mainContext.getBean('foo')
grailsApplication.mainContext.foo
在 Grails 2.2.5 中,我发现这可行:
grails-app/conf/Config.groovy
在适合您的环境的部分中配置您的变量。例如:environments { ... development { ... grails.config.myUrl = "http://localhost:3000" ...
...
访问:
import grails.util.Holders class myClass { ... def static myStaticMethod() { def myVar = Holders.config.grails.config.myUrl ...
我真的只想访问静态实用程序中的配置。在搜索并阅读了关于 SO 的大部分答案后,我提出了简单的解决方案(可能对某人有用):
在 src/groovy 下添加 holder 类:
class StaticContext {
static def app;
}
在 bootstrap init 中初始化它
class BootStrap {
def grailsApplication
def init = { servletContext ->
StaticContext.app = grailsApplication
}
def destroy = {
}
}
并在静态实用程序中访问它:
//In my case Solr URL in single ton
def solrUrl = StaticContext.app.config.solr.url