Chapter 39. Using A JAXBContext Object
Abstract
The JAXBContext
object allows the Apache CXF’s runtime to transform data between XML elements and Java object. Application developers need to instantiate a JAXBContext
object they want to use JAXB objects in message handlers and when implementing consumers that work with raw XML messages.
Overview
The JAXBContext
object 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 JAXBContext
objects. 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 JAXBContext
object using one of the two available JAXBContext.newInstance()
methods.
Best practices
JAXBContext
objects 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 JAXBContext
object that can manage all of the JAXB objects used by your application and share it among as many parts of your application as possible.
JAXBContext
objects are thread safe.
Getting a JAXBContext object using an object factory
The JAXBContext
class provides a newInstance()
method, shown in Example 39.1, “Getting a JAXB Context Using Classes”, that takes a list of classes that implement JAXB objects.
Example 39.1. Getting a JAXB Context Using Classes
staticJAXBContext
newInstance
Class…
classesToBeBound
JAXBException
The returned JAXBObject
object 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 JAXBContext
object will be able to manage any JAXB classes the specified object factories can instantiate.
Getting a JAXBContext object using package names
The JAXBContext
class provides a newInstance()
method, shown in Example 39.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 39.2. Getting a JAXB Context Using Classes
staticJAXBContext
newInstance
String
contextPath
JAXBException
The returned JAXBContext
object will be able to marshal and unmarshal data for all of the JAXB objects implemented by the classes in the specified packages.