Guide to JAXB – JAXB指南

最后修改: 2016年 12月 26日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

This is an introductory tutorial on JAXB (Java Architecture for XML Binding).

这是一个关于JAXB(Java Architecture for XML Binding)的介绍性教程。

First, we’ll show how to convert Java objects to XML and vice versa.

首先,我们将展示如何将Java对象转换成XML,反之亦然。

Then we’ll focus on generating Java classes from XML schema and vice versa by using the JAXB-2 Maven plugin.

然后,我们将重点讨论通过使用JAXB-2 Maven插件,从XML模式生成Java类,反之亦然。

2. Introduction to JAXB

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.

JAXB提供了一种快速而方便的方法来将Java对象编入(写)到XML中,并将XML解编(读)到对象中。它支持一个绑定框架,使用Java注释将XML元素和属性映射到Java字段和属性。

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

JAXB-2 Maven插件将其大部分工作委托给两个JDK提供的工具XJCSchemagen中的一个。

3. JAXB Annotations

3.JAXB注解

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

JAXB使用Java注解来增加生成的类的附加信息。在现有的Java类中加入这样的注解,可以为JAXB的运行做好准备。

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

让我们首先创建一个简单的Java对象来说明编组和解编。

@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.

关于JAXB注解的更多细节,请查看这个链接>。

4. Marshalling – Converting Java Object to XML

4.Marshalling – 将Java对象转换为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.

Marshalling使客户端应用程序能够将JAXB派生的Java对象树转换为XML数据。默认情况下,Marshaller在生成XML数据时使用UTF-8编码。接下来,我们将从Java对象中生成XML文件。

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:

让我们使用JAXBContext创建一个简单的程序,它为管理实现JAXB绑定框架操作所需的XML/Java绑定信息提供一个抽象。

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 javax.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.

javax.xml.bind.JAXBContext类提供了一个客户端到JAXB API的入口点。默认情况下,JAXB不对XML文档进行格式化。这可以节省空间并防止任何空白被意外地解释为重要的。

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.

为了让JAXB格式化输出,我们只需将Marshaller.JAXB_FORMATTED_OUTPUT属性设置为true,在Marshaller上。marshal方法使用一个对象和一个输出文件来存储生成的XML作为参数。

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:

当我们运行上面的代码时,我们可以在book.xml中检查结果,以验证我们已经成功地将一个Java对象转换成XML数据。

<?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. Unmarshalling – Converting XML to Java Object

5.解散–将XML转换为Java对象

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

取消洗牌使客户应用能够将XML数据转换为JAXB派生的Java对象。

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

让我们使用JAXB的Unmarshaller来把我们的book.xml解读为一个Java对象。

public Book unmarshall() 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:

当我们运行上面的代码时,我们可以检查控制台输出,以验证我们已经成功地将XML数据转换成了Java对象。

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

6. Complex Data Types

6.复杂的数据类型

When handling complex data types that may not be directly available in JAXB, we can write an adapter to indicate to JAXB how to manage a specific type.

当处理复杂的数据类型时,这些类型可能在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.

为了做到这一点,我们将使用 JAXB 的 XmlAdapter 来定义一个自定义代码,将不可应用的类转换为 JAXB 可以处理的东西。@XmlJavaTypeAdapter注解使用了一个扩展了XmlAdapter类的适配器来进行自定义编排。

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.

我们使用日期格式yyyy-MM-dd HH:mm:ss来将Date转换为String,并使用ThreadLocal来使我们的DateFormat具有线程安全。

Let’s apply the DateAdapter to our Book:

让我们将DateAdapter应用于我们的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:

当我们运行上面的代码时,我们可以在book.xml中检查结果,以验证我们已经成功地使用新的日期格式yyyy-MM-dd HH:mm:ss将我们的Java对象转换成XML。

<?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 Plugin

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.

这个插件使用Java API for XML Binding (JAXB), version 2+, 从XML模式(和可选的绑定文件)生成Java类,或者从一个有注释的Java类创建XML模式。

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.

请注意,有两种构建Web服务的基本方法:Contract LastContract First。关于这些方法的更多细节,请查看这个链接

7.1. Generating a Java Class From XSD

7.1.从XSD生成一个Java类

The JAXB-2 Maven plugin uses the JDK-supplied tool XJC, a JAXB Binding compiler tool that generates Java classes from XSD (XML Schema Definition).

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:

让我们创建一个简单的user.xsd文件,并使用JAXB-2 Maven插件从这个XSD模式生成Java类。

<?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:

我们来配置JAXB-2 Maven插件。

<plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>jaxb2-maven-plugin</artifactId>
    <version>2.3</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.

默认情况下,这个插件将XSD文件定位在src/main/xsd。我们可以通过修改pom.xml中该插件的配置部分来配置XSD查找。

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.

同样默认情况下,这些Java Classes是在target/generated-resources/jaxb文件夹中生成的。我们可以通过在插件配置中添加一个outputDirectory元素来改变输出目录。我们还可以添加一个clearOutputDir元素,其值为false,以防止此目录中的文件被删除。

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

此外,我们可以配置一个全局的JAXB绑定,覆盖默认的绑定规则。

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<jaxb:bindings version="2.0" xmlns:jaxb="http://java.sun.com/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"
            parse="javax.xml.bind.DatatypeConverter.parseDateTime"
            print="javax.xml.bind.DatatypeConverter.printDateTime" />
    </jaxb:globalBindings>
</jaxb:bindings>

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

上面的global.xjbdateTime类型重写为java.util.Calendar类型。

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

当我们构建项目时,它在src/main/java文件夹和com.baeldung.jaxb.gen包中生成了类文件。

7.2. Generating XSD Schema From Java

7.2.从Java生成XSD模式

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.

同一插件使用JDK提供的工具Schemagen。这是一个JAXB绑定编译器工具,可以从Java类中生成XSD模式。为了使一个Java类有资格成为XSD模式的候选者,该类必须用@XmlType注解来注释。

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

我们将重新使用前面例子中的Java类文件来配置该插件。

<plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>jaxb2-maven-plugin</artifactId>
    <version>2.3</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.

默认情况下,JAXB会递归地扫描src/main/java下的所有文件夹,以寻找注解的JAXB类。我们可以通过在插件配置中添加一个source元素,为我们的JAXB注释类指定一个不同的source文件夹。

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.

我们还可以注册一个transformSchemas,一个负责命名XSD模式的后处理器。它的工作原理是将namespace与我们Java类的@XmlType的命名空间相匹配。

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

当我们构建该项目时,它会在src/main/resources目录下生成一个user-gen.xsd文件。

8. Conclusion

8.结论

In this article, we covered introductory concepts on JAXB. For more details, take a look at the JAXB home page.

在这篇文章中,我们介绍了关于JAXB的介绍性概念。欲了解更多细节,请看JAXB主页

We can find the source code for this article over on GitHub.

我们可以在GitHub上找到这篇文章的源代码over