Dez 7 2010

Using JAXB for configuration-files

Frank

After a long break, I write again some tips and hints about Java programming.
Today I had again the problem that I need some configurable parameteres in an application. One way could be the usage of the Properties-API. But this only give us a very flat model.
In my eyes a better solution is to use XML. But this is very komplex to parse using DOM or SAX. So we can use some Binding-APIs to bind Java-Code to XML and vise versa.
One solution is XMLBeans, which I used in past. But from Java 6 on JAXB is included and so no extra library is needed.

So we start writing our Model in Java (I named it “Config”):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@XmlRootElement(name = "config", namespace = Config.NAMESPACE)
public class Config {
 
	public static final String NAMESPACE = "http://www.javahelp.info/test/config";
 
	private String host;
 
	@XmlElement(namespace = NAMESPACE)
	public String getHost() {
		return host;
	}
 
	public void setHost(String host) {
		this.host = host;
	}
}

That’s all. From now an you can read the config from a file with the following code:

1
2
3
4
5
JAXBContext context = JAXBContext.newInstance(Config.class);
Unmarshaller unmarshaller = context.createUnmarshaller();
//skip validation
unmarshaller.setSchema(null);
Config config = (Config) unmarshaller.unmarshal(new File("config.xml"));

And you also can write a in-memory-config:

1
2
3
4
5
6
Config config = new Config();
config.setHost("localhost");
 
JAXBContext context = JAXBContext.newInstance(Config.class);
Marshaller marshaller = context.createMarshaller();
marshaller.marshal(config, new File("config.xml"));