January 15
XStream, Aliases and Spring
by David Palmer
At some point in a complicated development project there will come a time when you need to translate a java object (assuming of course that you are working in java) into XML or back. Sure, we’ve all gone through the pain of Castor and the performance hits you take associated with that, and there are other tools, but what is now considered (by many) to be the standard is XStream. I won’t go into too much detail as to why XStream is as great as it is (two words: pull parsing), but suffice it to say it is, great.
XStream uses an aliasing feature so that you can “pretty up” your XML (by default XStream will just use the fully qualified package name for XML node names) which can be weird.
To use the aliasing feature, in your code, you simply do something like:
xstream.alias("node-name",MyClass.class);
Well, that’s all cool and all, but its very hard-coded. Wouldn’t it be cool if you could just wire something like this together in Spring?
There is a way to do this, its quite simple in fact. It just requires you to make an interface that defines a single method, something like: String:getNodeName(). Each class that must be serialized would implement said interface. Now, you just do something like the following in your Spring XML (in this case I created a configuration bean that contains a list of my “models” that must be serialized):
<bean id="config" class="com.marley.tmac.tools.Configuration">
<property id="serializableClass">
<list>
<bean class="com.marley.tmac.models.User"/>
<bean class="com.marley.tmac.models.UserElement"/>
</list>
</property>
</bean>
Now, in the class that handles setting up XStream, you would simply have something like:
for (YourInterface model : listFromSpring) {
xstream.alias(model.getNodeName(), model.getClass());
}
b1inder