制作Grails项目中几乎所有类都可以访问的变量的最佳做法是什么?是否有可用于存储该数据的配置文件(即application.properties)?
感谢。
答案 0 :(得分:25)
最好的选择是Config.groovy。任何类都可以访问ConfigurationHolder.getConfig(),使其成为全局变量,甚至可以为变量提供特定于环境的值。
someVar = "foo"
environments {
production {
grails.serverURL = "http://www.changeme.com"
someOtherVar = 1000
}
development {
grails.serverURL = "http://localhost:8080/${appName}"
someOtherVar = 100
}
test {
grails.serverURL = "http://localhost:8080/${appName}"
someOtherVar = 0
}
}
答案 1 :(得分:4)
使用Grails 2.2
//In Config.groovy
myVar = '/My/Root/Images/Folder'
//In your Services/Controllers/etc..
import grails.util.Holders
def grailsApplication = Holders.getGrailsApplication()
//access you variable
def myVar = grailsApplication.config.myVar;