Posts Tagged JAXB
How to add namespace attribute to XmlType Annotation in XJC generated Classes
Posted by Stephen Downey in Web Services on September 6, 2012
I recently came across a really frustrating issue on a client site when trying to marshal a webservice response. The client code was generated using the XJC compiler in ANT and worked fine in local unit tests and when called on a JBoss application server running locally. The problem occurred when we tried to run the same code on a old application server that is used in production. We kept getting the following error:
com.sun.xml.bind.v2.runtime.IllegalAnnotationsException: 219 counts of IllegalAnnotationExceptions Two classes have the same XML type name "". Use @XmlType.name and @XmlType.namespace to assign different names to them. this problem is related to the following location:
It looked like the other application server was not able to able to see the namespace for the generated classes that was generated in package-info.java. As a result there was a conflict with any class in the generated code with the same class name when the response was unmarshalled. We were using the standard Spring Jaxb2Marshaller so I know it could not be that:
……
I searched the web for information on how to add the namespace attribute to the generated classes but there were a lot of people looking for the same information and not answers:
How do I add a namespace attribute to an element in JAXB when marshalling?
Finally I found this page (http://www.java.net/node/655594) and the suggestion to use the “-npa” argument to the xjc compiler. This argument tells the compiler to suppress generation of package level annotations (**/package-info.java). You can see a full list of XJC commands here.
You can added it to the ant task as follows:
This will tell the XJC compiler to add the namespace attribute to the @XMLType annotation:
@XmlType(name = "GeneratedClass", namespace = "http://www.mynamespace.com/API/V2", propOrder = { "value" })
The marshaller is now able to map between the node in the response and the correct class.