1. 概述

这是 JAXB 是 Java Architecture for XML Binding 的缩写,用于将Java类映射为XML表示方式。

本文我们将演示如何将Java对象转换为XML,反之亦然。然后,我们将演示如何使用JAXB-2 Maven插件从XML schema 生成Java类,反之亦然。

2. JAXB简介

JAXB provides a fast and convenient way to marshal (write) Java objects into XML and unmarshal (read) XML into objects. It supports a binding framework that maps XML elements and attributes to Java fields and properties using Java annotations.

The JAXB-2 Maven plugin delegates most of its work to either of the two JDK-supplied tools XJC and Schemagen.

3. JAXB 注解

JAXB uses Java annotations to augment the generated classes with additional information. Adding such annotations to existing Java classes prepares them for the JAXB runtime.

Let’s first create a simple Java object to illustrate marshalling and unmarshalling:

@XmlRootElement(name = "book")
@XmlType(propOrder = { "id", "name", "date" })
public class Book {
    private Long id;
    private String name;
    private String author;
    private Date date;

    @XmlAttribute
    public void setId(Long id) {
        this.id = id;
    }

    @XmlElement(name = "title")
    public void setName(String name) {
        this.name = name;
    }

    @XmlTransient
    public void setAuthor(String author) {
        this.author = author;
    }
    
    // constructor, getters and setters
}

The class above contains these annotations:

  • @XmlRootElement: The name of the root XML element is derived from the class name, and we can also specify the name of the root element of the XML using its name attribute.
  • @XmlType: define the order in which the fields are written in the XML file
  • @XmlElement: define the actual XML element name that will be used
  • @XmlAttribute: define the id field is mapped as an attribute instead of an element
  • @XmlTransient: annotate fields that we don’t want to be included in XML

For more details on JAXB annotation, check out this link.

4. 序列化 – Java Object 转 XML

Marshalling gives a client application the ability to convert a JAXB-derived Java object tree into XML data. By default, the Marshaller uses UTF-8 encoding when generating XML data. Next, we will generate XML files from Java objects.

Let’s create a simple program using the JAXBContext, which provides an abstraction for managing the XML/Java binding information necessary to implement the JAXB binding framework operations:

public void marshal() throws JAXBException, IOException {
    Book book = new Book();
    book.setId(1L);
    book.setName("Book1");
    book.setAuthor("Author1");
    book.setDate(new Date());

    JAXBContext context = JAXBContext.newInstance(Book.class);
    Marshaller mar= context.createMarshaller();
    mar.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
    mar.marshal(book, new File("./book.xml"));
}

The jakarta.xml.bind.JAXBContext class provides a client’s entry point to JAXB API. By default, JAXB does not format the XML document. This saves space and prevents that any whitespace is accidentally interpreted as significant.

To have JAXB format the output, we simply set the Marshaller.JAXB_FORMATTED_OUTPUT property to true on the Marshaller. The marshal method uses an object and an output file to store the generated XML as parameters.

When we run the code above, we can check the result in the book.xml to verify that we have successfully converted a Java object into XML data:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<book id="1">
    <title>Book1</title>
    <date>2016-11-12T11:25:12.227+07:00</date>
</book>

5. 反序列化 – XML 转 Java Object

Unmarshalling gives a client application the ability to convert XML data into JAXB-derived Java objects.

Let’s use JAXB Unmarshaller to unmarshal our book.xml back to a Java object:

public Book unmarshal() throws JAXBException, IOException {
    JAXBContext context = JAXBContext.newInstance(Book.class);
    return (Book) context.createUnmarshaller()
      .unmarshal(new FileReader("./book.xml"));
}

When we run the code above, we can check the console output to verify that we have successfully converted XML data into a Java object:

Book [id=1, name=Book1, author=null, date=Sat Nov 12 11:38:18 ICT 2016]

6. 复杂数据类型

当处理复杂数据类型时,可能无法直接在JAXB中使用,我们可以编写适配器来指示JAXB如何管理特定类型。

To do this, we’ll use JAXB’s XmlAdapter to define a custom code to convert an unmappable class into something that JAXB can handle. The @XmlJavaTypeAdapter annotation uses an adapter that extends the XmlAdapter class for custom marshalling.

Let’s create an adapter to specify a date format when marshalling:

public class DateAdapter extends XmlAdapter<String, Date> {

    private static final ThreadLocal<DateFormat> dateFormat 
      = new ThreadLocal<DateFormat>() {

        @Override
        protected DateFormat initialValue() {
            return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        }
    };

    @Override
    public Date unmarshal(String v) throws Exception {
        return dateFormat.get().parse(v);
    }

    @Override
    public String marshal(Date v) throws Exception {
        return dateFormat.get().format(v);
    }
}

We use a date format yyyy-MM-dd HH:mm:ss to convert Date to String when marshalling and ThreadLocal to make our DateFormat thread-safe.

Let’s apply the DateAdapter to our Book:

@XmlRootElement(name = "book")
@XmlType(propOrder = { "id", "name", "date" })
public class Book {
    private Long id;
    private String name;
    private String author;
    private Date date;

    @XmlAttribute
    public void setId(Long id) {
        this.id = id;
    }

    @XmlTransient
    public void setAuthor(String author) {
        this.author = author;
    }

    @XmlElement(name = "title")
    public void setName(String name) {
        this.name = name;
    }

    @XmlJavaTypeAdapter(DateAdapter.class)
    public void setDate(Date date) {
        this.date = date;
    }
}

When we run the code above, we can check the result in the book.xml to verify that we have successfully converted our Java object into XML using the new date format yyyy-MM-dd HH:mm:ss:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<book id="1">
    <title>Book1</title>
    <date>2016-11-10 23:44:18</date>final
</book>

7. JAXB-2 Maven 插件

This plugin uses the Java API for XML Binding (JAXB), version 2+, to generate Java classes from XML Schemas (and optionally binding files) or to create XML schema from an annotated Java class.

Note that there are two fundamental approaches to building web services, Contract Last and Contract First. For more details on these approaches, check out this link.

7.1. 从 XSD 生成 Java 类

JAXB-2 Maven 插件使用 JDK-提供的工具 XJC,一个 JAXB 绑定编译器工具,用于从 XSD(XML Schema Definition)生成 Java 类。

Let’s create a simple user.xsd file and use the JAXB-2 Maven plugin to generate Java classes from this XSD schema:

<?xml version="1.0" encoding="UTF-8"?>
<schema xmlns="http://www.w3.org/2001/XMLSchema"
    targetNamespace="/jaxb/gen"
    xmlns:userns="/jaxb/gen"
    elementFormDefault="qualified">

    <element name="userRequest" type="userns:UserRequest"></element>
    <element name="userResponse" type="userns:UserResponse"></element>

    <complexType name="UserRequest">
        <sequence>
            <element name="id" type="int" />
            <element name="name" type="string" />
        </sequence>
    </complexType>

    <complexType name="UserResponse">
        <sequence>
            <element name="id" type="int" />
            <element name="name" type="string" />
            <element name="gender" type="string" />
            <element name="created" type="dateTime" />
        </sequence>
    </complexType>
</schema>

Let’s configure the JAXB-2 Maven plugin:

<plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>jaxb2-maven-plugin</artifactId>
    <version>3.1.0</version>
    <executions>
        <execution>
            <id>xjc</id>
            <goals>
                <goal>xjc</goal>
            </goals>
        </execution>
    </executions>
    <configuration>
        <xjbSources>
            <xjbSource>src/main/resources/global.xjb</xjbSource>
        </xjbSources>
        <sources>
            <source>src/main/resources/user.xsd</source>
        </sources>
        <outputDirectory>${basedir}/src/main/java</outputDirectory>
        <clearOutputDir>false</clearOutputDir>
    </configuration>
</plugin>

By default, this plugin locates XSD files in src/main/xsd. We can configure XSD lookup by modifying the configuration section of this plugin in the pom.xml accordingly.

Also by default, these Java Classes are generated in the target/generated-resources/jaxb folder. We can change the output directory by adding an outputDirectory element to the plugin configuration. We can also add a clearOutputDir element with a value of false to prevent the files in this directory from being erased.

Additionally, we can configure a global JAXB binding that overrides the default binding rules:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<jaxb:bindings version="3.0" xmlns:jaxb="https://jakarta.ee/xml/ns/jaxb"
    xmlns:xjc="http://java.sun.com/xml/ns/jaxb/xjc" xmlns:xs="http://www.w3.org/2001/XMLSchema"
    jaxb:extensionBindingPrefixes="xjc">

    <jaxb:globalBindings>
        <xjc:simple />
        <xjc:serializable uid="-1" />
        <jaxb:javaType name="java.util.Calendar" xmlType="xs:dateTime"
            parseMethod="jakarta.xml.bind.DatatypeConverter.parseDateTime"
            printMethod="jakarta.xml.bind.DatatypeConverter.printDateTime" />
    </jaxb:globalBindings>
</jaxb:bindings>

The global.xjb above overrides the dateTime type to the java.util.Calendar type.

When we build the project, it generates class files in the src/main/java folder and package com.baeldung.jaxb.gen.

7.2. 从 Java 生成 XSD Schema

The same plugin uses the JDK-supplied tool Schemagen. This is a JAXB Binding compiler tool that can generate an XSD schema from Java classes. In order for a Java Class to be eligible for an XSD schema candidate, the class must be annotated with a @XmlType annotation.

We’ll reuse the Java class files from the previous example to configure the plugin:

<plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>jaxb2-maven-plugin</artifactId>
    <version>3.1.0</version>
    <executions>
        <execution>
            <id>schemagen</id>
            <goals>
                <goal>schemagen</goal>
            </goals>
        </execution>
    </executions>
    <configuration>
        <sources>
            <source>src/main/java/com/baeldung/jaxb/gen</source>
        </sources>
        <outputDirectory>src/main/resources</outputDirectory>
        <clearOutputDir>false</clearOutputDir>
        <transformSchemas>
            <transformSchema>
                <uri>/jaxb/gen</uri>
                <toPrefix>user</toPrefix>
                <toFile>user-gen.xsd</toFile>
            </transformSchema>
        </transformSchemas>
    </configuration>
</plugin>

By default, JAXB recursively scans all the folders under src/main/java for annotated JAXB classes. We can specify a different source folder for our JAXB-annotated classes by adding a source element to the plugin configuration.

We can also register a transformSchemas, a post processor responsible for naming the XSD schema. It works by matching the namespace with the namespace of the @XmlType of our Java Class.

When we build the project, it generates a user-gen.xsd file in the src/main/resources directory.

8. 结论

在本文中,我们介绍了 JAXB 的一些基本概念。有关更多详细信息,请参阅 JAXB 主页

我们可以在 GitHub 上找到本文的源代码。