19.4 Property Placeholder Configuration

Grails supports the notion of property placeholder configuration through an extended version of Spring’s PropertyPlaceholderConfigurer.

Settings defined in either ConfigSlurper scripts or Java properties files can be used as placeholder values for Spring configuration in grails-app/conf/spring/resources.xml and grails-app/conf/spring/resources.groovy. For example given the following entries in grails-app/conf/application.groovy (or an externalized config):

  1. database.driver="com.mysql.jdbc.Driver"
  2. database.dbname="mysql:mydb"

You can then specify placeholders in resources.xml as follows using the familiar ${..} syntax:

  1. <bean id="dataSource"
  2. class="org.springframework.jdbc.datasource.DriverManagerDataSource">
  3. <property name="driverClassName">
  4. <value>${database.driver}</value>
  5. </property>
  6. <property name="url">
  7. <value>jdbc:${database.dbname}</value>
  8. </property>
  9. </bean>

To specify placeholders in resources.groovy you need to use single quotes:

  1. dataSource(org.springframework.jdbc.datasource.DriverManagerDataSource) {
  2. driverClassName = '${database.driver}'
  3. url = 'jdbc:${database.dbname}'
  4. }

This sets the property value to a literal string which is later resolved against the config by Spring’s PropertyPlaceholderConfigurer.

A better option for resources.groovy is to access properties through the grailsApplication variable:

  1. dataSource(org.springframework.jdbc.datasource.DriverManagerDataSource) {
  2. driverClassName = grailsApplication.config.database.driver
  3. url = "jdbc\:${grailsApplication.config.database.dbname}"
  4. }

Using this approach will keep the types as defined in your config.