Grails Cookbook - A collection of tutorials and examples

How to make Grails use an external properties file for datasource configuration

This tutorial will show how to use an external properties file to configure the datasource of a Grails application. Hardcoding database properties should only be limited for development purposes. But when deploying an application to another environment (E.g. test, UAT, production), it is usually convenient to be able to change things freely.

If you wish to set the datasource configuration via JNDI, follow this tutorial instead.

Configure Your Grails Application

Edit your Config.groovy file and add the following at the end:

grails.config.locations = [ "classpath:grails-app-config.properties"]

And then configure the production portion of your DataSource.groovy file like this:

environments {
...
    production {
        dataSource {
            dbCreate = ""
            driverClassName = ""
            url = ""
            username = ""
            password = ""
        }
    }
}

Notice that we can set the properties as blanks. We will override the values later in a properties file.

Prepare Properties File

Create the properties file. Below is the contents of grails-app-config.properties I created while testing this tutorial

dataSource.dbCreate=update
dataSource.driverClassName=com.mysql.jdbc.Driver
dataSource.url=jdbc:mysql://localhost:3306/myappdb
dataSource.username=root
dataSource.password=secret

Notice that I am using MySQL as the database for my test. You may change the values as you see fit to your scenario. Make sure also that you have the JDBC driver in your application server, or include them in your war.

Deploying To Tomcat

I used Tomcat 7 while testing this tutorial.
Deploy your war file to TOMCAT_HOME/webapps

The quick and dirty way to configure your app is to copy your grails-app-config.properties to TOMCAT_HOME/lib folder as it is in the classpath by default.

A cleaner way is to edit TOMCAT_HOME/conf/catalina.properties and define a folder where we can put all external properties file. For example, we can use a new folder like TOMCAT_HOME/props. Here is the contents of catalina.properties
...
common.loader=${catalina.base}/lib,${catalina.base}/lib/*.jar,${catalina.home}/lib,${catalina.home}/lib/*.jar,${catalina.home}/props
...
Notice that we added a new folder at the end of the line. This will be included to the classpath.
And now we could copy grails-app-config.properties to the dedicated folder.

Once you start your Tomcat server, the Grails application should be able to connect to the database correctly.