JAXB Continued: Generating Schema from Object Model
As I mentioned in the previous post, I like to start with my Java object model first and then bind the XML as required. There are obviously countless opinions on both sides of this argument. The two sides of the argument are contract-first and contract-last. As you can probably guess this refers to whether we define the XSD before we create the Java objects, or after we already have our object model coded up.
Spring WS makes the most convincing argument for contract-first design. In their reference documentation they defend their decision to only offer the contract-first option. They make some good points, and I agree, for very complex schemas it may be better to have a contract first so that both parties can have a way to validate their generated results. However, for a simpler model, as I’m going to show you, it’s very quick and painless to have JAXB generate a schema for you.
Let’s assume we’re using the same Prison schema:
I’m going to re-iterate again that it is a very simple schema, but that’s not really the point of this post. Now comes the COOL part! We generate the schema from the code by writing a quick unit test:
As you can see, there a couple of tricks to this – credit given to Amis blog. The first is that you’ll need to implement the SchemaOutputResolver interface, done here with an anonymous class that creates the DOMResult. The second is that you’ll need to output the result to System.out (and format it nicely of course!). Here is the generated result:
Pretty cool, right? Now you have an XSD schema! Obviously, the schema generator can’t guess the constraints for each field just from the Java code, so you’ll need to still modify this XSD. However, this can save you some work and will give you a great starting point for your XSD.
I’d love to hear some more feedback on the contract-first vs. contract-last last debate, so leave a comment!