Tuesday, June 16, 2015

JAXB - Concepts

JAXB : Java API for XML binding


We know that JAXB(Java API for XML Binding) allows Java developers to map Java classes to XML representations. JAXB provides two main features: the ability to marshal Java objects into XML and the inverse, i.e. to unmarshal XML back into Java objects. JAXB mostly is used while implementing webservices or any other such client interface for an application where data needs to be transferred in XML format instead of HTML format which is default in case of visual client like web browsers.


A good example is facebook APIs. Facebook has exposed its services through some open endpoints in form of RESTful webservices where you hit a URL and post some parameters, and API return you the data in xml format. Now it is upto you, how you use that data.


In this post, I am giving an example of marshalling and unmarshalling of Map objects e.g. HashMap. These map objects are usually represent the mapping between some simple keys to complex data.

Marshalling XML using O/X Mappers


As stated in the introduction, a marshaller serializes an object to XML, and an unmarshaller deserializes XML stream to an object. In this section, we will describe the two Spring interfaces used for this purpose.


Spring's OXM can be used for a wide variety of situations. In the following example, we will use it to marshal the settings of a Spring-managed application as an XML file. We will use a simple JavaBean to represent the settings


Marshallers could be configured more concisely using tags from the OXM namespace. To make these tags available, the appropriate schema has to be referenced first in the preamble of the XML configuration file. The emboldened text in the below snippet references the OXM schema:



The Jaxb1Marshaller class implements both the Spring Marshaller and Unmarshallerinterface. It requires a context path to operate, which you can set using the contextPathproperty. The context path is a list of colon (:) separated Java package names that contain schema derived classes. The marshaller has an additional validating property which defines whether to validate incoming XML.
The next sample bean configuration shows how to configure a JaxbMarshaller using the classes generated to org.springframework.ws.samples.airline.schema.

No comments:

Post a Comment