danb
danb

Reputation: 10379

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

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?

Upvotes: 36

Views: 28941

Answers (4)

jstricker
jstricker

Reputation: 2180

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)
    }
}

Upvotes: 10

khylo
khylo

Reputation: 4490

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?

Upvotes: 75

Robert Fischer
Robert Fischer

Reputation: 1443

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

Upvotes: 31

danb
danb

Reputation: 10379

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.

Upvotes: 14

Related Questions