Loading Properties from XML (revisited)
Posted by felipegaucho on October 29, 2007 at 3:23 PM EDT
My last blog about using JAXB instead of Properties for loading configuration of Java applications was a bit verbose - so, I decided to print a summary in order to facilitate the comprehension about the original proposal. I will not expose the discussion again, just present the below comparison sheet:
| java.util.Properties | JAXB |
|---|---|
| The configuration files: | |
text=word primitive=2 anobj.name=test anobj.integer=3 |
<?xml version="1.0" encoding="UTF-8" standalone="yes"?> <myConfig text="word" primitive="2"
><my.obj name=" test" integer="3"/></myConfig> |
| The code required for loading the configuration in the memory: | |
// Read properties file.
Properties properties = new Properties();
properties.load(new FileInputStream("filename.properties"));
|
// Unmarshal the properties XML file into a Java Object
JAXBContext jc = JAXBContext.newInstance(
AbstractJaxbFootprintStream.FOOTPRINT_CONTEXT, this.getClass()
.getClassLoader());
Unmarshaller unmarshaller = jc.createUnmarshaller();
unmarshaller.setEventHandler(new FootprintConfigValidationHandler());
unmarshaller.setListener(listener);
SchemaFactory sf = SchemaFactory
.newInstance(javax.xml.XMLConstants.W3C_XML_SCHEMA_NS_URI);
Schema schema = sf.newSchema(getClass().getClassLoader().getResource(
"config.xsd"));
unmarshaller.setSchema(schema);
MyConfig properties = (JAXBElement) unmarshaller
.unmarshal(new FileInputStream("filename.xml")).getValue();
|
| Reading the configuration values: | |
// A String:
String text = properties.getProperties("text");
// Other primitive values:
int number = Integer.parseInt(properties.getProperties("primitive"));
// An object:
String name = properties.getProperties("anobject.name");
int integer = properties.getProperties("anobject.integer");
Object yourObj = new YourObj(name, integer); |
// A String: String text = properties.getText(); // Other primitive values: int number = properties.getPrimitive(); // An object: Object yourObj = properties.getMyObject(); |
| My arguments for adopting JAXB instead of java.util.Properties: | |
|
|
* The title of this blog is an intentional reference to this 4 years old article.
Related Topics >>
Blog Links >>
- Printer-friendly version
- felipegaucho's blog
- 1402 reads





