Tuesday, September 15, 2009

Using Dynamic DB configuration based on the current value of Environment Variable in XML

A graphical depiction of a very simple xml doc...Image via Wikipedia

It has been a constant endeavor to segregate code dependency and provide loose coupling to ensure the same. That’s where XML comes into the picture helping us dynamically configure attributes required during runtime.

Here I have shown how to dynamically pull values from an environment variable and then use it in an xml file, thereby further promoting it for code usage. This is a common situation in environmental infrastructures, and code would depend on the current environment to build on the outgoing URLs/databases/queues/etc etc


Let’s take the picture of an app deployment which would connect to environment-wise database servers. We will assume that we will have a ENV_VAR user/system variable already defined on the box.

I have utilized spring’s PropertyPlaceholderConfigurer to feed a properties file which will contain the various db configs environment-wise:

<spring:beans>

<spring:bean class="org.springframework.beans. factory.config.PropertyPlaceholderConfigurer">

<spring:property name="location" value="classpath:dbconfig.properties"/>

</spring:bean>

</spring:beans>

Content of properties file(dbconfig.properties) with sample values:

devurl=jdbc:db2://someIP:30000/DB

devuser=username

devpass=password

produrl=jdbc:db2://someIP2:30000/DB

produser=user1

prodpass=pass1

Then in the xml config where we define the database configuration I picked up these dynamic values using:

<spring:property name="url" value="${${ENV_VAR}url}" />

<spring:property name="username" value="${${ENV_VAR}user}" />

<spring:property name="password" value="${${ENV_VAR}pass}" />

ENV_VAR should be an environment variable in each box i.e. ENV_VAR =dev for DEV box, ENV_VAR=prod for PROD blades etc

While server startup the values are picked up dynamically from the properties file depending on the value of the ENV_VAR environment variable on the application server box.

Thanks,

Yassar

Ø Email Blog

Reblog this post [with Zemanta]

No comments: