JAXB stands for Java Architecture for XML Binding. It provides a quick and convenient way to bind XML schemas and Java representations, making it easy for Java developers to read and write XML data without needing low-level XML parsers like DOM or SAX.
Key Concepts: Marshalling & Unmarshalling
Working with JAXB revolves around two fundamental operations:
Marshalling (Object to XML): The process of serializing a Java object tree into an XML document or stream.
Unmarshalling (XML to Object): The process of deserializing XML data back into a structured Java object.
Essential JAXB Annotations
To map your Java classes to XML structures, JAXB uses simple annotations:
@XmlRootElement: Defines the top-level root element of the XML document.
@XmlElement: Maps a Java field or getter/setter to an XML child tag.
@XmlAttribute: Maps a field as an attribute within an XML element.
@XmlElementWrapper: Generates a wrapper XML element around collection elements (such as a list of books).
Step-by-Step BookStore Example
1. Define the Book & BookStore Classes
Create your POJO classes and annotate them so JAXB knows how to convert the properties:
@XmlRootElement(name = "bookstore")
public class BookStore {
private String name;
private List<Book> bookList;
@XmlElement(name = "name")
public String getName() { return name; }
public void setName(String name) { this.name = name; }
@XmlElementWrapper(name = "bookList")
@XmlElement(name = "book")
public List<Book> getBookList() { return bookList; }
public void setBookList(List<Book> bookList) { this.bookList = bookList; }
}
2. Marshalling: Converting Java Object to XML
JAXBContext context = JAXBContext.newInstance(BookStore.class);
Marshaller marshaller = context.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
// Write to console or file
marshaller.marshal(bookStore, System.out);
JAXB (Java Architecture for XML Binding) provides a simple and clean API to convert Java objects into XML documents and vice versa. It removes the need for tedious manual parsing with DOM or SAX.
Core Operations in JAXB
Marshalling: Converting a Java object representation into an XML file or stream.
Unmarshalling: Reading an XML file or stream and converting it back into a Java object.
Annotations Used in Employee Example
@XmlRootElement: Specifies that the Employee class represents the root element in the generated XML.
@XmlAttribute: Configures a property (like id) to appear as an attribute of the XML root tag.
@XmlElement: Maps class fields (like name and salary) to child elements within the XML.
Step-by-Step Code Walkthrough
1. Annotated Employee Class
@XmlRootElement(name = "employee")
public class Employee {
private int id;
private String name;
private double salary;
public Employee() {}
public Employee(int id, String name, double salary) {
this.id = id;
this.name = name;
this.salary = salary;
}
@XmlAttribute(name = "id")
public int getId() { return id; }
public void setId(int id) { this.id = id; }
@XmlElement(name = "name")
public String getName() { return name; }
public void setName(String name) { this.name = name; }
@XmlElement(name = "salary")
public double getSalary() { return salary; }
public void setSalary(double salary) { this.salary = salary; }
}
Spring's Object/XML Mapping (OXM) framework simplifies XML binding by providing unified abstractions via Marshaller and Unmarshaller interfaces. Integrating Spring with JAXB (Java Architecture for XML Binding) enables seamless conversion between Java objects and XML documents with minimal configuration.
Key Concepts
Marshalling: Converting a Java object graph into an XML representation.
Unmarshalling: Parsing an XML document and instantiating corresponding Java objects.
Jaxb2Marshaller: The central Spring OXM class that implements both Spring's Marshaller and Unmarshaller interfaces.
Step-by-Step Implementation
1. Define the JAXB Annotated Model Class
@XmlRootElement(name = "customer")
public class Customer {
private int id;
private String name;
private int age;
@XmlAttribute(name = "id")
public int getId() { return id; }
public void setId(int id) { this.id = id; }
@XmlElement(name = "name")
public String getName() { return name; }
public void setName(String name) { this.name = name; }
@XmlElement(name = "age")
public int getAge() { return age; }
public void setAge(int age) { this.age = age; }
}
2. Configure Spring Jaxb2Marshaller
Configure the Spring bean definition to bind the target classes to be bound:
Company company = new Company();
company.setId(201);
company.setCompanyName("Google");
company.setCeoName("Peter");
company.setNumberOfEmployees(50000);
// Perform Unmarshaling
Company company2 = (Company) unmarshaller
.unmarshal(newStreamSource(newFileReader("company.xml"))); System.out.println(company2); System.out.println("Converted XML to Object!");
} }
Output:
XML Created Sucessfully
Company [id=201, companyName=Google, ceoName=Peter, numberOfEmployees=50000]
Converted XML to Object!
Introduction: What is XML Marshalling and Unmarshalling?
In modern software development, converting Java objects to XML and vice versa is a common requirement for data exchange. This process is known as Object-XML Mapping (OXM):
Marshalling: Converting a Java object into an XML document format.
Unmarshalling: Reading an XML document and deserializing it back into a Java object.
Why Use Spring OXM with JAXB?
Spring provides an abstraction layer through the Spring OXM module, which simplifies working with different XML binding frameworks like JAXB (Java Architecture for XML Binding). Using annotation-based configuration makes your code cleaner, easier to maintain, and eliminates the need for bulky XML mapping files.
Key Steps Covered in This Tutorial
Model Setup: Annotating the Java domain class using standard JAXB annotations (@XmlRootElement, @XmlElement, etc.).
Spring Configuration: Configuring Jaxb2Marshaller using Java-based @Configuration without external XML configs.
Executing Marshalling: Converting the Java entity instance into an XML file stream.
Executing Unmarshalling: Reading back the XML file and validating the restored Java object properties.
Company company = new Company();
company.setId(201);
company.setCompanyName("Google");
company.setCeoName("Peter");
company.setNumberOfEmployees(50000);
// from object to XML file
converter.convertFromObjectToXML(company, XML_FILE_NAME); System.out.println("Converted Object to XML!");
// from XML to object
Company company2 = (Company) converter
.convertFromXMLToObject(XML_FILE_NAME); System.out.println(company2); System.out.println("Converted XML to Object!");
} }
Output:
Converted Object to XML!
Company [id=201, companyName=Google, ceoName=Peter, numberOfEmployees=50000]
Converted XML to Object!