Spring教程-Spring与JAXB集成示例

Spring与JAXB集成示例
JAXB是Java Architecture for XML Binding的缩写,它允许Java开发人员将Java类映射到XML表示形式中。JAXB可用于将Java对象编组为XML,反之亦然。
这是一种由Sun提供的OXM(对象XML映射)或O/M框架。
JAXB的优势
无需创建或使用SAX或DOM解析器以及编写回调方法。
Spring与JAXB集成示例(将Java对象编组为XML)
您需要创建以下文件,以便在Spring中使用JAXB将Java对象编组为XML:
Employee.java
这个类定义了三个属性:id、name和salary。在这个类中,我们使用了以下注解:
- @XmlRootElement:它指定XML文件的根元素。
- @XmlAttribute:它为属性指定属性。
- @XmlElement:它指定元素。
package cn.javatiku;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name="employee")
public class Employee {
private int id;
private String name;
private float 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 float getSalary() {
return salary;
}
public void setSalary(float salary) {
this.salary = salary;
}
}
applicationContext.xml
在这个文件中,我们定义了一个名为jaxbMarshallerBean
的bean,其中将Employee类与OXM框架进行了绑定。
<?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="jaxbMarshallerBean">
<oxm:class-to-be-bound name=" cn.javatiku.Employee"/>
</oxm:jaxb2-marshaller>
</beans>
Client.java
这个类从applicationContext.xml
文件中获取Marshaller的实例,并调用marshal方法。
package cn.javatiku;
import java.io.FileWriter;
import java.io.IOException;
import javax.xml.transform.stream.StreamResult;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.oxm.Marshaller;
public class Client{
public static void main(String[] args)throws IOException{
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
Marshaller marshaller = (Marshaller)context.getBean("jaxbMarshallerBean");
Employee employee=new Employee();
employee.setId(101);
employee.setName("Sonoo Jaiswal");
employee.setSalary(100000);
marshaller.marshal(employee, new StreamResult(new FileWriter("employee.xml")));
System.out.println("XML Created Sucessfully");
}
}
示例的输出
employee.xml
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<employee id="101">
<name>Sonoo Jaiswal</name>
<salary>100000.0</salary>
</employee>