Wednesday, February 18, 2009

Grails: reading configuration at runtime

As far as You know some basic configuration in Your Grails application is located in Config.groovy (under grails-app/conf folder). Often it is very useful to access data from it at runtime. To do that You have to use org.codehaus.groovy.grails.commons.ConfigurationHolder. For example, let's read SMTP properties from one of the previous posts.

Config.groovy:
// Some simple SMTP configuration.
grails {
mail {
host = "smtp.gmail.com"
port = 465
username = "youracount@gmail.com"
password = "yourpassword"
props = ["mail.smtp.auth":"true"]
}
}

Some service, for instance Email service:
// Using import aliasing.
import org.codehaus.groovy.grails.commons.ConfigurationHolder
as confHolder

class EmailService {

def sendEmail() {
// Reading property by name.
def username = confHolder.config.grails.mail.username
}

}

As You can see its very simple. In order to have access to Grails configuration from controllers or tags use grailsApplication: in our case grailsApplication.config.grails.mail.username. Enjoy!

No comments:

Post a Comment