After getting some interesting feedback from an anonymous reader, I decided to transform the example in the previous post from JAXB first to XSD first. The updated code can be found in the
xsdfirst branch of the memberservice project at github.
What had to be done?
1. The JAXB message classes had to be deleted since they are now being generated based on an XSD using the XJC compiler (actually the
pom.xml had to be updated to include this new plugin, and the
schemagen ant task had to be removed.
3. Since the generated java code was updated (for instance, one of the constructors that I had previously is not generated), I had to refactor almost all classes that depend upon the message classes.
4. I also had to update the XSD, since XJC otherwise would not generate domain objects that could be marshalled automatically (XJC did’t add @XmlRootElement annotations on the request/response classes). I’ve created a small project at github that demonstrates the differences.
5. I added restrictions to some of the elements in the XSD in order to address some of the issues pointed out to me in the previous post. Unfortuanately, the restrictions are not converted into java code. Therefore, in order to make sure only valid data is input/output from the WS interface, the schema has to be added to the jaxb2marshaller configuration in
applicationContext.xml. I hope the JAXB team will add bean validation support to the XJC compiler.
Pros and cons of this approach
- - Little control over the generated JAXB classes. Cannot add custom code directly.
- - Given XJC’s behaviour, the XSD has to be written in a certain way in order to make the code work as expected
- + Support for restrictions/validation based on XSD schema restrictions