RSS Feed for This PostCurrent Article

Java – Using Multiple Configuration Files in Your Application

Download Source

I have the need to use multiple configuration files in my Java application. One is a properties file, another is a XML file. This can be done easily using Apache Commons Configuration.

I created a singleton class AppConfigCactory which extends CompositeConfiguration

public class AppConfigFactory extends CompositeConfiguration {

private static Log log = LogFactory.getLog(AppConfigFactory.class);
private static AppConfigFactory instance;
private static String configFile = “config.xml”;

// Singleton initialiser
static {
instance = new AppConfigFactory(configFile);
}

/**
* Constructor
*
* @param fileName Configuration file name.
*/
private AppConfigFactory(String fileName) {
init(fileName);
}

/**
* Initialize the class.
*
* @param fileName Configuration file name.
*/
private void init(String fileName) {
try {
ConfigurationFactory factory = new ConfigurationFactory(fileName);
Configuration config = factory.getConfiguration();
addConfiguration(config);
} catch (ConfigurationException configEx) {
log.error(configEx.getMessage());
configEx.printStackTrace();
}
}

/**
* Singleton access method.
*
* @return Singleton
*/
public static AppConfigFactory getInstance() {
return instance;
}
}

In config.xml I specified the properties and XML file that I wanted to load.

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

<configuration>
<properties fileName=”file.properties”/>
<xml fileName=”file.xml”/>
</configuration>

file.properties contains

myproperty=properties testing

file.xml contains

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

<app-config>
<value>XML testing</value>
</app-config>
</config>

To test the code,

public static void main(String[] args){
AppConfigFactory config = AppConfigFactory.getInstance();

// From properties file
System.out.println(config.getString(“myproperty”));

// From XML file
System.out.println(config.getString(“app-config.value”));
}

The output,

properties testing
XML testing


Trackback URL


Sorry, comments for this entry are closed at this time.