Spring Oxm 简明教程

Spring OXM - Quick Guide

Spring OXM - Overview

Spring 框架使用全局 marshall/unmarshall 接口提供对象/XML 或 O/X 映射,并允许轻松切换 O/X 映射框架。将对象转换为 XML 的此过程称为 XML 编组/序列化,而将 XML 转换为对象的过程称为 XML 解编组/反序列化。

The Spring Framework provides Object/XML or O/X mapping using global marshaller/unmarshaller interfaces and allows to switch O/X mapping frameworks easily. This process of converting an object to XML is called XML Marshalling/Serialization and conversion from XML to object is called XML Demarshalling/Deserialization.

Spring 框架提供了一个 Marshall 和 UnMarshaller 接口,其中 Marshall 接口负责将对象编组到 XML,而 UnMarshaller 接口将 xml 反序列化到一个对象。以下是使用 Spring OXM 框架的主要优点。

Spring framework provides a Marshaller and UnMarshaller interfaces where Marshaller interface is responsible to marshall an object to XML and UnMarshaller interface deserializes the xml to an object. Following are the key benefits of using Spring OXM framework.

  1. Easy Configuration − Using spring bean context factory, creation of marshaller/unmarshaller is quite easy and is configurable without worrying about O/X libraries structures like JAXB Context, JiBX binding factories etc. A marsaller/unmarshaller can be configured as any other bean.

  2. Consistent Interfacing − Marshaller and UnMarshaller are global interfaces. These interfaces provides an abstraction layer over other O/X mapping frameworks and allows to switch between them without changing the code or with little code change.

  3. Consistent Exception Handling − All underlying exceptions are mapped to a XmlMappingException as root exception. Thus developers need not to worry about underlying O/X mapping tool own exception hiearchy.

Marshaller

Marshaller 是一个具有单个方法 marshal 的接口。

Marshaller is an interface with single method marshal.

public interface Marshaller {
   /**
      * Marshals the object graph with the given root into the provided Result.
   */
   void marshal(Object graph, Result result)
      throws XmlMappingException, IOException;
}

其中 graph 是要编组的任意对象,而 result 是表示 XML 输出的标记接口。以下是可用类型−

Where graph is any object to be marshalled and result is a tagging interface to represent the XML output. Following are the available types −

  1. javax.xml.transform.dom.DOMResult − Represents org.w3c.dom.Node.

  2. javax.xml.transform.sax.SAXResult − Represents org.xml.sax.ContentHandler.

  3. javax.xml.transform.stream.StreamResult − Represents java.io.File, java.io.OutputStream, or java.io.Writer.

UnMarshaller

UnMarshaller 是一个具有单个方法 unmarshal 的接口。

UnMarshaller is an interface with single method unmarshal.

public interface UnMarshaller {
   /**
      * Unmarshals the given provided Source into an object graph.
   */
   Object unmarshal(Source source)
      throws XmlMappingException, IOException;
}

其中 source 是用于表示 XML 输入的标记化界面。以下是可用的类型:

Where source is a tagging interface to represent the XML input. Following are the available types −

  1. javax.xml.transform.dom.DOMSource − Represents org.w3c.dom.Node.

  2. javax.xml.transform.sax.SAXSource − Represents org.xml.sax.InputSource, and org.xml.sax.XMLReader.

  3. javax.xml.transform.stream.StreamSource − Represents java.io.File, java.io.InputStream, or java.io.Reader.

Spring OXM - Environment Setup

本章将在您开始使用 Spring 框架时,指导您如何准备开发环境。它还将教您在设置 Spring 框架之前如何在您的机器上设置 JDK、Maven 和 Eclipse −

This chapter will guide you on how to prepare a development environment to start your work with Spring Framework. It will also teach you how to set up JDK, Maven and Eclipse on your machine before you set up Spring Framework −

Setup Java Development Kit (JDK)

你可以从 Oracle 的 Java 站点下载 SDK 的最新版本 − Java SE Downloads. 你在下载文件中可以找到安装 JDK 的说明,按照给定的说明进行安装和配置。最后设置 PATH 和 JAVA_HOME 环境变量以引用包含 java 和 javac 的目录,通常分别为 java_install_dir/bin 和 java_install_dir。

You can download the latest version of SDK from Oracle’s Java site − Java SE Downloads. You will find instructions for installing JDK in downloaded files, follow the given instructions to install and configure the setup. Finally set PATH and JAVA_HOME environment variables to refer to the directory that contains java and javac, typically java_install_dir/bin and java_install_dir respectively.

如果您运行的是 Windows 且在 C:\jdk-11.0.11 中安装了 JDK,那么您将不得不把以下代码行放入您的 C:\autoexec.bat 文件中。

If you are running Windows and have installed the JDK in C:\jdk-11.0.11, you would have to put the following line in your C:\autoexec.bat file.

set PATH=C:\jdk-11.0.11;%PATH%
set JAVA_HOME=C:\jdk-11.0.11

或者,在 Windows NT/2000/XP 中,你必须右键单击我的电脑,选择属性 → 高级 → 环境变量。然后,你将不得不更新 PATH 值并单击确定按钮。

Alternatively, on Windows NT/2000/XP, you will have to right-click on My Computer, select Properties → Advanced → Environment Variables. Then, you will have to update the PATH value and click the OK button.

在 Unix(Solaris、Linux 等)中,如果 SDK 安装在 /usr/local/jdk-11.0.11 且您使用 C shell,那么您将不得不把以下代码行放入您的 .cshrc 文件中。

On Unix (Solaris, Linux, etc.), if the SDK is installed in /usr/local/jdk-11.0.11 and you use the C shell, you will have to put the following into your .cshrc file.

setenv PATH /usr/local/jdk-11.0.11/bin:$PATH
setenv JAVA_HOME /usr/local/jdk-11.0.11

或者,如果你使用诸如 Borland JBuilder、Eclipse、IntelliJ IDEA 或 Sun ONE Studio 这样的集成开发环境 (IDE),则必须编译并运行一个简单程序来确认 IDE 知道你在何处安装了 Java。否则,你必须按照 IDE 文档中给出的内容执行正确的设置。

Alternatively, if you use an Integrated Development Environment (IDE) like Borland JBuilder, Eclipse, IntelliJ IDEA, or Sun ONE Studio, you will have to compile and run a simple program to confirm that the IDE knows where you have installed Java. Otherwise, you will have to carry out a proper setup as given in the document of the IDE.

Setup Eclipse IDE

本教程中的所有示例都是使用 Eclipse IDE 编写的。因此,我们建议你应该在你机器上安装 Eclipse 的最新版本。

All the examples in this tutorial have been written using Eclipse IDE. So we would suggest you should have the latest version of Eclipse installed on your machine.

要安装 Eclipse IDE,请从 www.eclipse.org/downloads 下载最新的 Eclipse 二进制文件。下载安装文件后,将二进制分发包解压到方便的位置。例如,在 Windows 上的 C:\eclipse 中,或 Linux/Unix 上的 /usr/local/eclipse 中,最后相应地设置 PATH 变量。

To install Eclipse IDE, download the latest Eclipse binaries from www.eclipse.org/downloads. Once you download the installation, unpack the binary distribution into a convenient location. For example, in C:\eclipse on Windows, or /usr/local/eclipse on Linux/Unix and finally set PATH variable appropriately.

可以通过在 Windows 机器上执行以下命令启动 Eclipse,或者你只需双击 eclipse.exe

Eclipse can be started by executing the following commands on Windows machine, or you can simply double-click on eclipse.exe

%C:\eclipse\eclipse.exe

可以通过在 Unix(Solaris、Linux 等)机器上执行以下命令启动 Eclipse −

Eclipse can be started by executing the following commands on Unix (Solaris, Linux, etc.) machine −

$/usr/local/eclipse/eclipse

成功启动后,如果一切正常,它应该显示以下结果 −

After a successful startup, if everything is fine then it should display the following result −

eclipsehomepage

Set Maven

在本教程中,我们使用 maven 来运行和构建基于 Spring 的示例。请按照 Maven - Environment Setup 安装 maven。

In this tutorial, we are using maven to run and build the spring based examples. Follow the Maven - Environment Setup to install maven.

Spring OXM - Create Project

在 Eclipse 中,选择 FileNewMaven Project 。勾选 *创建简单项目(跳过原型选择)*并单击下一步。

Using eclipse, select FileNewMaven Project. Tick the *Create a simple project (skip archetype selection) * and click Next.

按照以下所示输入详细信息 −

Enter the details, as shown below −

  1. groupId − com.tutorialspoint

  2. artifactId − springoxm

  3. version − 0.0.1-SNAPSHOT

  4. name − Spring OXM

  5. description − Spring OXM Project

单击完成按钮,将创建一个新项目。

Click on Finish button and an new project will be created.

pom.xml

您可以查看 pom.xml 的默认内容

You can check the default content of pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">

   <modelVersion>4.0.0</modelVersion>
   <groupId>com.tutorialspoint</groupId>
   <artifactId>springoxm</artifactId>
   <version>0.0.1-SNAPSHOT</version>
   <name>Spring OXM</name>
   <description>Spring OXM Project</description>
</project>

现在我们的项目已经准备就绪,在下一章中,让我们在 pom.xml 中添加以下依赖项。

Now as we’ve our project ready, let add following dependencies in pom.xml in next chapter.

  1. Spring Core

  2. Spring OXM

  3. JAXB

Spring OXM - Update Project JAXB2

按照下面所示更新 pom.xml 的内容,使其包含 Spring core、Spring oxm 和 jaxb 依赖项:

Update the content of pom.xml to have spring core, spring oxm and jaxb dependencies as shown below −

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">

   <modelVersion>4.0.0</modelVersion>
   <groupId>com.tutorialspoint</groupId>
   <artifactId>springoxm</artifactId>
   <version>0.0.1-SNAPSHOT</version>
   <name>Spring OXM</name>
   <description>Spring OXM Project</description>
   <properties>
      <org.springframework.version>4.3.7.RELEASE</org.springframework.version>
      <org.hibernate.version>5.2.9.Final</org.hibernate.version>
      <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
      <java.version>1.8</java.version>
   </properties>
   <dependencies>
      <dependency>
         <groupId>org.springframework</groupId>
         <artifactId>spring-context</artifactId>
         <version>${org.springframework.version}</version>
         <scope>compile</scope>
      </dependency>
      <dependency>
         <groupId>org.springframework</groupId>
         <artifactId>spring-oxm</artifactId>
         <version>${org.springframework.version}</version>
         <scope>compile</scope>
      </dependency>
      <dependency>
         <groupId>javax.xml.bind</groupId>
         <artifactId>jaxb-api</artifactId>
         <version>2.3.1</version>
      </dependency>
      <dependency>
         <groupId>org.glassfish.jaxb</groupId>
         <artifactId>jaxb-runtime</artifactId>
         <version>2.3.1</version>
         <scope>runtime</scope>
      </dependency>
   </dependencies>
   <build>
      <plugins>
         <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.1</version>
            <configuration>
               <source>${java.version}</source>
               <target>${java.version}</target>
            </configuration>
         </plugin>
      </plugins>
   </build>
</project>

按照下面所示使用 O/X 注解创建 Student.java 类。

Create a class Student.java with O/X Annotation as shown below.

Student.java

package com.tutorialspoint.oxm.model;

import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class Student{
   String name;
   int age;
   int id;

   public String getName(){
      return name;
   }
   @XmlElement
   public void setName(String name){
      this.name = name;
   }
   public int getAge(){
      return age;
   }
   @XmlElement
   public void setAge(int age){
      this.age = age;
   }
   public int getId(){
      return id;
   }
   @XmlAttribute
   public void setId(int id){
      this.id = id;
   }
}

在 *src → main → resources * 中创建 applicationcontext.xml,其内容如下。

Create applicationcontext.xml in *src → main → resources * with the following content.

applicationcontext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xmlns:oxm="http://www.springframework.org/schema/oxm"
   xsi:schemaLocation="http://www.springframework.org/schema/beans
   http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
   http://www.springframework.org/schema/oxm
   http://www.springframework.org/schema/oxm/spring-oxm-3.0.xsd">

   <oxm:jaxb2-marshaller id="jaxbMarshaller">
      <oxm:class-to-be-bound name="com.tutorialspoint.oxm.model.Student"/>
   </oxm:jaxb2-marshaller>
</beans>

Spring OXM - Test JAXB2

使用 marshall 和 unmarshall 对象创建主类 OXMApplication.java 。此类的目的是使用 marshall 对象将学生对象编组到 student.xml,然后使用 unmarshall 对象将 student.xml 解编组到 student 对象。

Create a main class OXMApplication.java with marshaller and unmarshaller objects. The objective of this class is to marshall a student object to student.xml using marshaller object and then unmarshall the student.xml to student object using unmarshaller object.

Example

OXMApplication.java

OXMApplication.java

package com.tutorialspoint.oxm;

import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.oxm.Marshaller;
import org.springframework.oxm.Unmarshaller;
import org.springframework.oxm.XmlMappingException;
import com.tutorialspoint.oxm.model.Student;

public class OXMApplication {
   public static void main(String[] args) {
      ApplicationContext context = new ClassPathXmlApplicationContext("applicationcontext.xml");
      Marshaller marshaller = (Marshaller)context.getBean("jaxbMarshaller");
      Unmarshaller unmarshaller = (Unmarshaller)context.getBean("jaxbMarshaller");

      // create student object
      Student student = new Student();
      student.setAge(14);
      student.setName("Soniya");

      try {
         marshaller.marshal(student, new StreamResult(new FileWriter("student.xml")));
         System.out.println("Student marshalled successfully.");
         FileInputStream is =  new FileInputStream("student.xml");
         Student student1 = (Student)unmarshaller.unmarshal(new StreamSource(is));
         System.out.println("Age: " + student1.getAge() + ", Name: " + student1.getName());
      } catch(IOException | XmlMappingException ex) {
         ex.printStackTrace();
      }
   }
}

Output

在 Eclipse 中的文件内容区中单击鼠标右键,然后选择 Run as java application 并验证输出。

Right click in the content area of the file in eclipse and then select Run as java application and verify the output.

Oct 10, 2021 8:48:12 PM org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@1e127982: startup date
[Sun Oct 10 20:48:12 IST 2021]; root of context hierarchy
Oct 10, 2021 8:48:12 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [applicationcontext.xml]
Oct 10, 2021 8:48:13 PM org.springframework.oxm.jaxb.Jaxb2Marshaller createJaxbContextFromClasses
INFO: Creating JAXBContext with classes to be bound [class com.tutorialspoint.oxm.model.Student]
Student marshalled successfully.
Age: 14, Name: Soniya

Spring OXM - Update Project XStream

按照下面所示更新 pom.xml 的内容,使其包含 xstream 依赖项:

Update the content of pom.xml to have xstream dependencies as shown below −

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">

   <modelVersion>4.0.0</modelVersion>
   <groupId>com.tutorialspoint</groupId>
   <artifactId>springoxm</artifactId>
   <version>0.0.1-SNAPSHOT</version>
   <name>Spring OXM</name>
   <description>Spring OXM Project</description>
   <properties>
      <org.springframework.version>4.3.7.RELEASE</org.springframework.version>
      <org.hibernate.version>5.2.9.Final</org.hibernate.version>
      <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
      <java.version>1.8</java.version>
   </properties>
   <dependencies>
      <dependency>
         <groupId>org.springframework</groupId>
         <artifactId>spring-context</artifactId>
         <version>${org.springframework.version}</version>
         <scope>compile</scope>
      </dependency>
      <dependency>
         <groupId>org.springframework</groupId>
         <artifactId>spring-oxm</artifactId>
         <version>${org.springframework.version}</version>
         <scope>compile</scope>
      </dependency>
      <dependency>
         <groupId>com.thoughtworks.xstream</groupId>
         <artifactId>xstream</artifactId>
         <version>1.4.8</version>
         <scope>compile</scope>
      </dependency>
   </dependencies>
   <build>
      <plugins>
         <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.1</version>
            <configuration>
               <source>${java.version}</source>
               <target>${java.version}</target>
            </configuration>
         </plugin>
      </plugins>
   </build>
</project>

按照下面所示更新 Student.java 类。

Update the class Student.java as shown below.

Student.java

package com.tutorialspoint.oxm.model;

public class Student {
   String name;
   int age;
   int id;

   public String getName(){
      return name;
   }
   public void setName(String name){
      this.name = name;
   }
   public int getAge(){
      return age;
   }
   public void setAge(int age){
      this.age = age;
   }
   public int getId(){
      return id;
   }
   public void setId(int id){
      this.id = id;
   }
}

在 *src → main → resources * 中使用下列内容更新 applicationcontext.xml,以便使用 XStreamMarshaller。XStreamMarshaller 对象可用于编组和解组。

Update applicationcontext.xml in *src → main → resources * with the following content to use XStreamMarshaller. XStreamMarshaller object can be used for both marshalling and unmarshalling.

applicationcontext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xmlns:oxm="http://www.springframework.org/schema/oxm"
   xsi:schemaLocation="http://www.springframework.org/schema/beans
   http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
   http://www.springframework.org/schema/oxm
   http://www.springframework.org/schema/oxm/spring-oxm-3.0.xsd">

   <bean id="xstreamMarshaller" class="org.springframework.oxm.xstream.XStreamMarshaller">
      <property name="annotatedClasses" value="com.tutorialspoint.oxm.model.Student"></property>
   </bean>
</beans>

Spring OXM - Test XStream

使用 marshall 和 unmarshall 对象更新主类 OXMApplication.java 。此类的目的是使用 marshall 对象将学生对象编组到 student.xml,然后使用 unmarshall 对象将 student.xml 解编组到 student 对象。

Update the main class OXMApplication.java with marshaller and unmarshaller objects. The objective of this class is to marshall a student object to student.xml using marshaller object and then unmarshall the student.xml to student object using unmarshaller object.

Example

OXMApplication.java

OXMApplication.java

package com.tutorialspoint.oxm;

import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.oxm.Marshaller;
import org.springframework.oxm.Unmarshaller;
import org.springframework.oxm.XmlMappingException;
import com.tutorialspoint.oxm.model.Student;

public class OXMApplication {
   public static void main(String[] args) {
      ApplicationContext context = new ClassPathXmlApplicationContext("applicationcontext.xml");
      Marshaller marshaller = (Marshaller)context.getBean("xstreamMarshaller");
      Unmarshaller unmarshaller = (Unmarshaller)context.getBean("xstreamMarshaller");

      // create student object
      Student student = new Student();
      student.setAge(14);
      student.setName("Soniya");

      try {
         marshaller.marshal(student, new StreamResult(new FileWriter("student.xml")));
         System.out.println("Student marshalled successfully.");
         FileInputStream is =  new FileInputStream("student.xml");
         Student student1 = (Student)unmarshaller.unmarshal(new StreamSource(is));
         System.out.println("Age: " + student1.getAge() + ", Name: " + student1.getName());
      } catch(IOException | XmlMappingException ex) {
         ex.printStackTrace();
      }
   }
}

Output

在 Eclipse 中的文件内容区中单击鼠标右键,然后选择 Run as java application 并验证输出。

Right click in the content area of the file in eclipse and then select Run as java application and verify the output.

Oct 11, 2021 9:18:37 AM org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@29ca901e: startup date
[Mon Oct 11 09:18:36 IST 2021]; root of context hierarchy
Oct 11, 2021 9:18:37 AM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [applicationcontext.xml]
WARNING: An illegal reflective access operation has occurred
WARNING: Illegal reflective access by com.thoughtworks.xstream.core.util.Fields
(file:/C:/Users/intel/.m2/repository/com/thoughtworks/xstream/xstream/1.4.8/xstream-1.4.8.jar)
to field java.util.TreeMap.comparator
WARNING: Please consider reporting this to the maintainers of com.thoughtworks.xstream.core.util.Fields
WARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operations
WARNING: All illegal access operations will be denied in a future release
Student marshalled successfully.
Age: 14, Name: Soniya

Spring OXM - Update Project Castor

按照下面所示更新 pom.xml 的内容,使其包含 castor 依赖项:

Update the content of pom.xml to have castor dependencies as shown below −

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">

   <modelVersion>4.0.0</modelVersion>
   <groupId>com.tutorialspoint</groupId>
   <artifactId>springoxm</artifactId>
   <version>0.0.1-SNAPSHOT</version>
   <name>Spring OXM</name>
   <description>Spring OXM Project</description>
   <properties>
      <org.springframework.version>4.3.7.RELEASE</org.springframework.version>
      <org.hibernate.version>5.2.9.Final</org.hibernate.version>
      <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
      <java.version>1.8</java.version>
   </properties>
   <dependencies>
      <dependency>
         <groupId>org.springframework</groupId>
         <artifactId>spring-context</artifactId>
         <version>${org.springframework.version}</version>
         <scope>compile</scope>
      </dependency>
      <dependency>
         <groupId>org.springframework</groupId>
         <artifactId>spring-oxm</artifactId>
         <version>${org.springframework.version}</version>
         <scope>compile</scope>
      </dependency>
      <dependency>
         <groupId>org.codehaus.castor</groupId>
         <artifactId>castor-core</artifactId>
         <version>1.4.1</version>
      </dependency>
      <dependency>
         <groupId>org.codehaus.castor</groupId>
         <artifactId>castor-xml</artifactId>
         <version>1.4.1</version>
      </dependency>
   </dependencies>
   <build>
      <plugins>
         <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.1</version>
            <configuration>
               <source>${java.version}</source>
               <target>${java.version}</target>
            </configuration>
         </plugin>
      </plugins>
   </build>
</project>

src → main → resources * 文件夹中添加一个 castor 映射所需的映射 xml,以便将 *Student 类映射为 mappings.xml ,如下所示:

Add a mapping xml required for castor mapping to map Student class as mappings.xml under *src → main → resources * folder as shown below.

mappings.xml

<?xml version="1.0"?>
<!DOCTYPE mapping PUBLIC "-//EXOLAB/Castor Mapping DTD Version 1.0//EN" "http://castor.org/mapping.dtd">
<mapping>
   <class name="com.tutorialspoint.oxm.model.Student" auto-complete="true" >
      <map-to xml="Student"/>
      <field name="id" type="integer">
         <bind-xml name="id" node="attribute"></bind-xml>
      </field>
      <field name="name">
         <bind-xml name="name"></bind-xml>
      </field>
      <field name="age">
         <bind-xml name="age" type="int"></bind-xml>
      </field>
   </class>
</mapping>

在 *src → main → resources * 中使用下列内容更新 applicationcontext.xml,以便使用 CastorMarshaller。CastorMarshaller 对象可用于编组和解组。

Update applicationcontext.xml in *src → main → resources * with the following content to use CastorMarshaller. CastorMarshaller object can be used for both marshalling and unmarshalling.

applicationcontext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xmlns:oxm="http://www.springframework.org/schema/oxm"
   xsi:schemaLocation="http://www.springframework.org/schema/beans
   http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
   http://www.springframework.org/schema/oxm
   http://www.springframework.org/schema/oxm/spring-oxm-3.0.xsd">

   <bean id="castorMarshaller" class="org.springframework.oxm.castor.CastorMarshaller">
      <property name="targetClass" value="com.tutorialspoint.oxm.model.Student"></property>
      <property name="mappingLocation" value="mappings.xml"></property>
   </bean>
</beans>

Spring OXM - Test Castor

使用 marshall 和 unmarshall 对象更新主类 OXMApplication.java 。此类的目的是使用 marshall 对象将学生对象编组到 student.xml,然后使用 unmarshall 对象将 student.xml 解编组到 student 对象。

Update the main class OXMApplication.java with marshaller and unmarshaller objects. The objective of this class is to marshall a student object to student.xml using marshaller object and then unmarshall the student.xml to student object using unmarshaller object.

Example

OXMApplication.java

OXMApplication.java

package com.tutorialspoint.oxm;

import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.oxm.Marshaller;
import org.springframework.oxm.Unmarshaller;
import org.springframework.oxm.XmlMappingException;
import com.tutorialspoint.oxm.model.Student;

public class OXMApplication {
   public static void main(String[] args) {
      ApplicationContext context = new ClassPathXmlApplicationContext("applicationcontext.xml");
      Marshaller marshaller = (Marshaller)context.getBean("castorMarshaller");
      Unmarshaller unmarshaller = (Unmarshaller)context.getBean("castorMarshaller");

      // create student object
      Student student = new Student();
      student.setAge(14);
      student.setName("Soniya");

      try {
         marshaller.marshal(student, new StreamResult(new FileWriter("student.xml")));
         System.out.println("Student marshalled successfully.");
         FileInputStream is =  new FileInputStream("student.xml");
         Student student1 = (Student)unmarshaller.unmarshal(new StreamSource(is));
         System.out.println("Age: " + student1.getAge() + ", Name: " + student1.getName());
      } catch(IOException | XmlMappingException ex) {
         ex.printStackTrace();
      }
   }
}

Output

在 Eclipse 中的文件内容区中单击鼠标右键,然后选择 Run as java application 并验证输出。

Right click in the content area of the file in eclipse and then select Run as java application and verify the output.

Oct 11, 2021 9:45:34 AM org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@6adede5: startup date
[Mon Oct 11 09:45:34 IST 2021]; root of context hierarchy
Oct 11, 2021 9:45:35 AM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [applicationcontext.xml]
WARNING: An illegal reflective access operation has occurred
WARNING: Illegal reflective access by org.exolab.castor.xml.BaseXercesOutputFormat
(file:/C:/Users/intel/.m2/repository/org/codehaus/castor/castor-xml/1.4.1/castor-xml-1.4.1.jar)
to method com.sun.org.apache.xml.internal.serialize.OutputFormat.setMethod(java.lang.String)
WARNING: Please consider reporting this to the maintainers of org.exolab.castor.xml.BaseXercesOutputFormat
WARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operations.
WARNING: All illegal access operations will be denied in a future release
Student marshalled successfully.
Age: 14, Name: Soniya