Parameterize Spring applicationContext with properties file

Spring has a very useful class called PropertyPlaceholderConfigurer that helps you to parameterize your applicationContext.xml file. In order to use this, you will need to add the bean in spring like this




/WEB-INF/spring-config/dev.properties




where the property location points to the list of properties files.

I use this primarily becasue
1. easier to maintain properties in a properties file than applicationContext
2. switch between different environments, e.g. development vs. staging vs. production

An example of the use of this would be

/WEB-INF/web.xml


org.springframework.web.context.ContextLoaderListener



contextConfigLocation
/WEB-INF/applicationContext.xml



/WEB-INF/spring-config/dev.properties

# Dev DB Setting
mysql.driver=com.mysql.jdbc.Driver
mysql.url=jdbc:mysql://dev.mydomain.com:3306/
mysql.username=devuser
mysql.password=xxx

/WEB-INF/spring-config/prod.properties

# Product DB Setting
mysql.driver=com.mysql.jdbc.Driver
mysql.url=jdbc:mysql://prod.mydomain.com:3306/
mysql.username=produser
mysql.password=xxx

/WEB-INF/applicationContext.xml




/WEB-INF/spring-config/dev.properties













To switch between environments, all you have to update is


/WEB-INF/spring-config/prod.properties

in the applicationContext.xml

To make it fancier, of course you can supply the properties to an ant script when you build your application.

Comments (0)

Post a Comment