How to create global variables in a Grails project

前端 未结 2 2060
孤城傲影
孤城傲影 2021-02-07 22:02

What\'s the best practice of making a variable that would be accessible by almost all classes in a Grails project? Is there a config file that I can use for storage of that data

相关标签:
2条回答
  • 2021-02-07 22:33

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

    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
       }
    }
    
    0 讨论(0)
  • 2021-02-07 22:42

    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;
    
    0 讨论(0)
提交回复
热议问题