Spring JAXB
spring jaxb
jaxb是 用于xml绑定的java体系结构的首字母缩写。它允许java开发人员将java类映射为xml表示形式。 jaxb可用于将java对象编组为xml,反之亦然。
它是sun提供的oxm(对象xml映射)或o/m框架。
jaxb的优势无需创建或使用sax或dom解析器,也无需编写回调方法。
spring和jaxb集成的示例(将java对象编组为xml)
您需要为创建以下文件使用带有jaxb的spring将java对象编组为xml:
- employee.java
- applicationcontext.xml
- client.java
必需的jar文件
要运行此示例,您需要加载:
- spring core jar文件
- spring web jar文件
下载spring的所有jar文件,包括core,web,aop,mvc,j2ee,remoting ,oxm,jdbc,orm等。
employee.java
如果定义了三个属性id,名称和薪水。我们在此类中使用了以下注释:
- @xmlrootelement 它指定xml文件的根元素。
- @xmlattribute 它指定属性的属性。
- @xmlelement 它指定元素。
package com.yapf;
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
它定义了一个bean jaxbmarshallerbean,其中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="com.yapf.employee"/>
</oxm:jaxb2-marshaller>
</beans>
client.java
它从applicationcontext.xml文件获取marshaller的实例并调用marshal方法。
package com.yapf;
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>


