RSS Feed for This PostCurrent Article

XML Configuration for Java Program

Download Source Code

Nowadays Java is widely used to code backend program, e.g. running batch job, doing extraction, transaction, and loading, etc. For all the program, the configuration can be in properties file, or XML file. Apache Commons Configuration is used for this purpose. I have written a singleton class which uses Commons Configuration for this purpose.

Below is the sample configuration file

<?xml version=”1.0″ encoding=”ISO-8859-1″ ?>
<config>

    <database>
<user-name>db-user</user-name>
<password>db-passwd</password>
</database>

<lists>
<list>1</list>
<list>2</list>
<list>3</list>
</lists>

<batch-job>
<job>
<name>Job1</name>
</job>
<job>
<name>Job2</name>
</job>
</batch-job>
</config>

The code to access the configurations.

AppConfig config = AppConfig.getInstance();
System.out.println(config.getString("database.user-name"));
System.out.println(config.getString("database.password"));

Object obj = config.getProperty("lists.list");
if (obj instanceof Collection) {
int size = ((Collection) obj).size();
for (int i = 0; i < size; i++) {
System.out.println(config.getProperty("lists.list(" + i + ")"));
}
} else if (obj instanceof String) {
System.out.println(config.getProperty("lists.list"));
}

obj = config.getProperty("batch-job.job.name");
if (obj instanceof Collection) {
int size = ((Collection) obj).size();
for (int i = 0; i < size; i++) {
System.out.println(config.getProperty("batch-job.job(" + i + ").name"));
}
} else if (obj instanceof String) {
System.out.println(config.getProperty("batch-job.job.name"));
}


Trackback URL