grailsgrails-config

Grails 2.0 use configuration value from external file in POGO


Here is the scenario. I have an file outside of my Grails application that contains url/username/password/etc. information so that developers can not see the connection information for production. I'm including this information in the Config.groovy by doing:

grails.config.locations << "file:" + "C:/directory/from/env/variable/data.properties"

Then I was accessing this information in a POGO via:

import org.codehaus.groovy.grails.commons.ConfigurationHolder
...
ConfigurationHolder.config.url
ConfigurationHolder.config.userName
ConfigurationHolder.config.password

After upgrading to Grails 2.0 I noticed that the ConfigurationHolder is deprecated. So I went to the documentation: ( http://grails.org/doc/latest/guide/conf.html) to try and figure out how to fix it. The documentation says to use the grailsApplication to get a hold of config values. My problem is that I'm in a POGO and the Grails autowiring of the grailsApplication does not get invoked. My question has 2 parts:

1) Is there a better way to get configuration information out of a file while inside of a POGO?

2) If there isn't a better way, how do I inject the grailsApplication into a POGO?

ADDITIONAL INFORMATION: I'm using the Grails GLDAPO plugin ( http://gldapo.codehaus.org/) to interface with an LDAP directory. I'm trying to make these objects (which I've placed under /src/groovy) act the same way as domain objects in that I can have static methods on them to do findBy...(..). With the pattern that you're suggesting I'd HAVE to go through a service to fetch data. Which isn't bad it's just not as Groovy :)


Solution

  • New answer based on updated question.

    You have a few options. One is to wire in the grailsApplication to the metaclass for these classes, i.e. in BootStrap.groovy:

    class BootStrap {
    
       def grailsApplication
    
       def init = { servletContext ->
          YourClass.metaClass.getGrailsApplication = { -> grailsApplication }
       }
    }
    

    This would add a getGrailsApplication method that can be accessed as the grailsApplication property.

    Another option is to add a static grailsApplication field to these classes and set that in BootStrap:

    class BootStrap {
    
       def grailsApplication
    
       def init = { servletContext ->
          YourClass.grailsApplication = grailsApplication
       }
    }
    

    Also see this blog post that discusses creating holder classes and this one that discusses overriding constructors.