Accessing Grails Configuration with Spring Property Placeholders
It seems like everybody approaches the issue of accessing their configuration from their application code in a different way. Grails gives us some helpful shortcuts that make accessing the configuration pretty easy. Simply injecting the
<a href="http://grails.org/doc/latest/api/org/codehaus/groovy/grails/commons/GrailsApplication.html">grailsApplication</a>bean in any of your controllers or services will let you access the magical
<a href="http://grails.org/doc/latest/api/org/codehaus/groovy/grails/commons/GrailsApplication.html#getConfig()">config</a>property. From there, all global and environment-specific configurations are available as attributes of the
<a href="http://groovy.codehaus.org/gapi/groovy/util/ConfigObject.html">ConfigObject</a>instance, and can be accessed with JavaBean-style ‘dot’ notation.
A common approach that I’ve seen in Grails applications is to create a
ConfigurationServicewith helper methods for accessing the config. You can think of this approach as a shortcut, but it probably adds a layer of unnecessary abstraction when you want to be more explicit. It also means having another service to maintain, when you really just need a variable representing a configuration value.
Luckily, Grails is a fully loaded Spring application and the framework developers have gone to great lengths to ensure that the Grails abstraction integrates seamlessly within the Spring application context. To that end, we can realize that the Grails configuration is exposed to the Spring
<a href="http://static.springsource.org/spring/docs/3.1.x/javadoc-api/org/springframework/core/env/Environment.html">Environment</a>and the directives therein are able to be accessed with property placeholder expressions throughout the application.
Now, in your services and controllers you can explicitly wire properties for the configuration directive that you need by using Spring’s
<a href="http://static.springsource.org/spring/docs/3.1.x/javadoc-api/org/springframework/beans/factory/annotation/Value.html">@Value</a>annotation. Consider the following configuration and service that demonstrates using Spring’s constructs to assign configuration values to variables within a service.
It’s important to note the single quotes in the annotation value field. This is necessary due to Groovy and the Spring Expression Language (SpEL) sharing the same notation for evaluating expressions. In this case, we don’t want Groovy to try to interpret this as an expression, as it will only make sense to the SpEL parser.