Copyright © 2022-2025 aizws.net · 网站版本: v1.2.6·内部版本: v1.25.2·
页面加载耗时 0.00 毫秒·物理内存 137.8MB ·虚拟内存 1372.6MB
欢迎来到 AI 中文社区(简称 AI 中文社),这里是学习交流 AI 人工智能技术的中文社区。 为了更好的体验,本站推荐使用 Chrome 浏览器。
JAXB是 用于XML绑定的Java体系结构的首字母缩写。它允许Java开发人员将Java类映射为XML表示形式。 JAXB可用于将Java对象编组为XML,反之亦然。
它是Sun提供的OXM(对象XML映射)或O/M框架。
JAXB的优势无需创建或使用SAX或DOM解析器,也无需编写回调方法。
您需要为创建以下文件使用带有JAXB的Spring将Java对象编组为XML:
要运行此示例,您需要加载:
下载spring的所有jar文件,包括core,web,aop,mvc,j2ee,remoting ,oxm,jdbc,orm等。
Employee.java
如果定义了三个属性id,名称和薪水。我们在此类中使用了以下注释:
package com.aizws;
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.aizws.Employee"/>
</oxm:jaxb2-marshaller>
</beans>
Client.java
它从applicationContext.xml文件获取Marshaller的实例并调用marshal方法。
package com.aizws;
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>
Spring Java Mail: Spring框架提供了许多用于发送和接收邮件的有用接口和类。 org.springframework.mail 软件包是在Spring框架中提供邮件支持的根软件包。 Spring Ja ...