Grails 2.0 use configuration value from external file in POGO

1.3k Views Asked by At

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

2

There are 2 best solutions below

0
On BEST ANSWER

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.

1
On

You must be calling it from an artifact that can dependency-inject the grailsApplication bean, at least indirectly. Add def grailsApplication to the service or Quartz job or whatever is calling your POGO and pass grailsApplication.config to it either for method calls that need it, or once in a setter.