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
grailsApplicationbean in any of your controllers or services will let you access the magical
configproperty. From there, all global and environment-specific configurations are available as attributes of the
ConfigObjectinstance, 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
Environmentand 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
@Valueannotation. 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.