Wednesday, July 14, 2010

Using Apache Ant as template engine while building an Application

Target audience: Beginners
There will be situations where we may have more than one properties files having same values for keys. For Example, there can be different properties files but have the same value for server URL or JNDI Provider URL. These values will vary depends on the environment we deploy the Application. For Example, Server URL will be in UAT (User Acceptance Testing) environment and it will be in production. We have to change all the places in all properties file whenever we deploy the application. It is Ok, if it’s only in one or two places. But what if there are several places to be changed and lot of values like this Server URL. It’ll be a headache.

What can be done?
What we can do is, we can use keys for all the configuration values and replace all the keys with the actual values when the application is built.

Let me explain, we can use a key for Server URL and this key will be used in all properties file. Where ever the Server URL is used, this key will be used instead. Ok, Assume that now we are going to use a key myapp.config.serverurl in all the places where Server URL is used. And we are going to replace this key with the actual value when we build the application. The idea is to replace all the actual values while building. We can keep the actual values in a configuration file with key value pair.

It sounds better, and how can we do this?
We can do this with Apache Ant. As you all know, Ant is a Java-based build tool widely used for building java projects. We can make use of replace task and do out work.Suppose, My application has properties file called, then I’ll make a file and myapp.config files. The file will have all configuration values replace with keys and the myapp.config will have entries for those keys and values. At the build time the Ant build system that I am going to create will generate the final file which will be used for deployment

I keep all files, myapp.config and build.xml in one folder and file also will be generated in the same folder


The myapp.config

Ant build file

includes="*.properties" />

Once you run the ant task, the file will be generated. The generated file will look like the following

No comments:

Post a Comment