How do I get at the goodies in my Grails Config.groovy at runtime?

风格不统一 提交于 2019-12-17 21:52:29

问题


in Config.groovy I see this:

// set per-environment serverURL stem for creating absolute links
environments {
    production {
        grails.serverURL = "http://www.changeme.com"
    }
}

what is the correct way to access that at runtime?


回答1:


danb is on the right track. However, life gets a bit easier on your fingers if you do a nicer import:

import org.codehaus.groovy.grails.commons.ConfigurationHolder as CH
println CH.config.grails.serverURL



回答2:


In more recent versions of grails ConfigurationHolder has been deprecated.

Instead you should use the grailsApplication object.

grailsApplication.config.grails.serverURL

If in a Controller or Service then use dependency injection of grailsApplication object. e.g.

class MyController{
    def grailsApplication
    def myAction() {
        grailsApplication.config.grails.serverURL
    }

See How to access Grails configuration in Grails 2.0?




回答3:


here it is:

import org.codehaus.groovy.grails.commons.ConfigurationHolder
println ConfigurationHolder.config.grails.serverURL

alternatively, in controllers and tags, apparently this will work:

grailsApplication.config.grails.serverURL

I needed it in BootStrap, so option 1 was what I needed.




回答4:


As mentioned in a few of the comments, another option is the grails.utils.Holders class which was added in Grails 2.0. I prefer this approach since you can use it in classes that aren't configured with dependency injection.

import grails.util.Holders

class Foo {
    def bar() {
        println(Holders.config.grails.serverURL)
    }
}


来源:https://stackoverflow.com/questions/198365/how-do-i-get-at-the-goodies-in-my-grails-config-groovy-at-runtime

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!