Grails外部配置在第一次加载时读取不正确

时间:2011-08-24 14:32:10

标签: grails configuration

Grails 1.3.7

我在外部配置文件中有一些配置。其中一个entires看起来像这样:

site.maintenance.mode = false

我有一个过滤器,用于检查特定网址的某些配置设置。当我执行run-app或将WAR部署到Tomcat并执行:

boolean maintenanceMode = grailsApplication.config.site.maintenance.mode

maintenanceMode回归正确。如果我在调试模式下查看配置对象,这就是我得到的:

site={maintenance={mode=false, message="<p>Our trail guides are working hard to get the system back on track.</p><p>We're sorry, the account system is down for maintenance at the moment.  We'll get it back online as quickly as we can.  Thanks for your patience.</p>"}}

我有一个控制器用于动态重新加载此配置文件,点击此控制器将解决问题。但我很好奇为什么它在第一次运行时是不正确的,以及为什么在维护模式变量中放入的内容与在配置对象中的实际内容之间存在差异。

2 个答案:

答案 0 :(得分:5)

您使用的是Java属性文件还是Groovy文件?如果您正在使用属性文件,那么我相信Grails会像site.maintenance.mode=false一样解释site.maintenance.mode='false',因为Groovy会解释:

"false".asBoolean() == true

那么这就解释了为什么你会看到最初的真实价值。

我刚刚在本地运行了一个简单的测试来验证这种行为。当我在名为test.properties的文件中外部化我的属性时,site.maintenance.mode=false最初得到一个布尔值true,当我使用一个名为test.groovy的文件时,它会解释布尔值site.maintenance.mode=false为假。我相信这是因为当您使用Groovy文件时,Grails使用ConfigurationSlurper来处理它,但是当您使用属性文件时,Grails会将所有内容解释为String名称/值对。

答案 1 :(得分:-1)

我所做的是拥有一个外部Config.groovy文件,例如:MyConfig.groovy

在标准grails Config.groovy文件的末尾,我有以下内容:

def ENV_NAME = "MY_EXTERNAL_CONFIG"
if(!grails.config.locations || !(grails.config.locations instanceof List)) {
    grails.config.locations = []
}
if(System.getenv(ENV_NAME)) {
    grails.config.locations << "file:" + System.getenv(ENV_NAME)
} else if(System.getProperty(ENV_NAME)) {
    grails.config.locations << "file:" + System.getProperty(ENV_NAME)
} else {
    println "No external Configs found."
}

所以现在你可以在生产环境中的任何地方(例如)拥有一个MyConfig.groovy文件,然后在启动tomcat之前将环境系统变量设置为指向该文件(或将其作为参数传递给startup.sh):

MY_EXTERNAL_CONFIG="/home/tomcat/configs/MyConfig.groovy"
export MY_EXTERNAL_CONFIG

就是这样。现在您有一个外部MyConfig.groovy文件。其中的属性可以从您的grails应用程序访问,因为它们是标准Config.groovy

的一部分
import org.codehaus.groovy.grails.commons.*
//... 
ConfigurationHolder.config.foo.bar.hello