Properties Configuration with XStream

Thanks to Mig's archives. I was able to rescue this old post.

August 16, 2004

Jared OdulioProperties configuration with XStream

Yes the spelling is correct, I am referring to XStream Java to XML Serialization API. For simple configurations, we could settle for Java Properties API where we can just define a properties file with key/value pair construct and load it to a Properties instance then that's it. But what if we need a more flexible configuration in XML without being overwhelmed with which XML parser to use and what performs best? A good bet would be XStream for a simple XML-based configuration you can quickly use XStream almost as you would with Java Properties API. To make that a little quicker, here's little quick and dirty sample.

Let's say we have an application that automates an administration of two remote servers via SSH so we need to keep the hostname, port, username and password(!!!) in the configuration file. First we need to define the xml configuration file:





Then let's use a value object named "ServerConfig".

public class ServerConfig{

private String host;
private String port;
private String username;
private String password;

//Constructors here..

//Getters and Setters here


Then a configuration manager class called "ConfigManager".

public class ConfigManager{

private List configs;
private XStream xstream;

public ConfigManager(){

xstream = new XStream(); //this constructor uses the XML Pull Parser 3 API

xstream.alias("linked-list", ArrayList.class);
xstream.alias("serverconfig", ServerConfig.class);

//Assumes that your config file is in the classpath.
InputStream is = this.getClass().getResourceAsStream("/serverconfig.xml");
InputStreamReader reader = new InputStreamReader(is);
configs = (List)xstream.fromXML(reader);


public List getConfigs(){

return configs;


An admin class might look something like this:

public class MainAdmin{

public static void main(String[] args){

ConfigManager manager = new ConfigManager();
List servers = manager.getConfigs();
ServerConfig config = null;
Iterator it = servers.iterator();
config = (ServerConfig);

The output will be:

August 16, 2004 08:39 PM


Popular Posts