Language and Page Formatting Options
Chapter 37. Using A JAXBContext Object
JAXBContextobject allows the Apache CXF's runtime to transform data between XML elements and Java object. Application developers need to instantiate a
JAXBContextobject they want to use JAXB objects in message handlers and when implementing consumers that work with raw XML messages.
JAXBContextobject is a low-level object used by the runtime. It allows the runtime to convert between XML elements and their corresponding Java representations. An application developer generally does not need to work with
JAXBContextobjects. The marshaling and unmarshaling of XML data is typically handled by the transport and binding layers of a JAX-WS application.
However, there are instances when an application will need to manipulate the XML message content directly. In two of these instances:
You will need instantiate a
JAXBContextobject using one of the two available
JAXBContextobjects are resource intensive to instantiate. It is recommended that an application create as few instances as possible. One way to do this is to create a single
JAXBContextobject that can manage all of the JAXB objects used by your application and share it among as many parts of your application as possible.
JAXBContextobjects are thread safe.
Getting a JAXBContext object using an object factory
JAXBContextclass provides a
newInstance()method, shown in Example 37.1, “Getting a JAXB Context Using Classes”, that takes a list of classes that implement JAXB objects.
Example 37.1. Getting a JAXB Context Using Classes
static JAXBContext newInstance(Class... classesToBeBound)
JAXBObjectobject will be able to marshal and unmarshal data for the JAXB object implemented by the classes passed into the method. It will also be able to work with any classes that are statically referenced from any of the classes passed into the method.
While it is possible to pass the name of every JAXB class used by your application to the
newInstance()method it is not efficient. A more efficient way to accomplish the same goal is to pass in the object factory, or object factories, generated for your application. The resulting
JAXBContextobject will be able to manage any JAXB classes the specified object factories can instantiate.
Getting a JAXBContext object using package names
JAXBContextclass provides a
newInstance()method, shown in Example 37.2, “Getting a JAXB Context Using Classes”, that takes a colon (
:) seperated list of package names. The specified packages should contain JAXB objects derived from XML Schema.
Example 37.2. Getting a JAXB Context Using Classes
static JAXBContext newInstance(String contextPath)
JAXBContextobject will be able to marshal and unmarshal data for all of the JAXB objects implemented by the classes in the specified packages.