Monday, January 22, 2007

Configuring Grails datasource with a .properties file

A Grails user needs to configure Grails data sources with an external .properties file (posted here), but having Spring beans inside "resources.xml" for it won't work for some reasons. I was trying to investigate what's going on, and found that there're steps done by Grails Hibernate plugin to retrieve references of datasouce before some beans defined in "resources.xml" are processed.

Anyway, I like the concept of using .properties file as well. So I modified *some*DataSource.groovy to see how can I use .properties to fill the data source properties, and here's the code:

import java.util.Properties
import org.springframework.core.io.FileSystemResource

class DevelopmentDataSource {

def static propFile = "web-app/WEB-INF/conf.properties";

boolean pooling = true
String dbCreate = "create-drop"

String url
String driverClassName
String username
String password

public DevelopmentDataSource() {
def props = new Properties()
try {
props.load(new FileSystemResource(propFile).inputStream)
} catch(Exception e){
e.printStackTrace();
}
this.driverClassName = props.getProperty("jdbc.driver","org.hsqldb.jdbcDriver")
this.url = props.getProperty("jdbc.url","jdbc:hsqldb:mem:inDB")
this.username = props.getProperty("jdbc.username","sa")
this.password = props.getProperty("jdbc.password","")
}
}


I know that it's not an elegant solution for the moment, but it works :).
With this modified datasource, you use the "propFile" to point to some file outside .WAR, and have some better level of abstraction.

2 comments:

Anonymous said...

It's can't work at grails1.0.3!!

chanwit said...

Hi,

This trick is out dated.
I think Grails 1.0.3 provides a better way of doing this. Please check its document.