How to create global variables in a Grails project

What's the best practice for making a variable available to almost all classes in a Grails project? Is there a config file I can use to store this data (like application.properties)?

Thanks.

+12


a source to share


2 answers


Your best bet is Config.groovy. Any class can access ConfigurationHolder.getConfig () which makes it global, and you can even have environment dependent variable values.



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

      

+25


a source


With 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;

      

+4


a source







All Articles