Spring与XStream集成示例

XStream 是一个用于将对象序列化为XML格式,以及反之亦然,而无需任何映射文件的库。请注意,Castor 需要一个映射文件。

XStreamMarshaller 类提供了将对象编组为XML以及将XML反编组为对象的功能。

Spring与XStream集成示例(将Java对象编组为XML)

要使用Spring与XStream将Java对象编组为XML,您需要创建以下文件:

Employee.java

这个类定义了三个属性:id、name和salary,以及对应的setter和getter方法。

package cn.javatiku;  
public class Employee {  
private int id;  
private String name;  
private float salary;  
  
public int getId() {  
    return id;  
}  
public void setId(int id) {  
    this.id = id;  
}  
public String getName() {  
    return name;  
}  
public void setName(String name) {  
    this.name = name;  
}  
public float getSalary() {  
    return salary;  
}  
public void setSalary(float salary) {  
    this.salary = salary;  
}  
}  

applicationContext.xml

在这个文件中,我们定义了一个名为xstreamMarshallerBean的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"  
    xsi:schemaLocation="http://www.springframework.org/schema/beans   
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">  
      
<bean id="xstreamMarshallerBean" class="org.springframework.oxm.xstream.XStreamMarshaller">  
    <property name="annotatedClasses" value="cn.javatiku.Employee"></property>  
</bean>  
</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("xstreamMarshallerBean");  
          
  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

<cn.javatiku.Employee>  
<id>101</id>  
<name>Sonoo Jaiswal</name>  
<salary>100000.0</salary>  
</cn.javatiku.Employee>  

标签: spring, Spring教程, Spring技术, Spring语言学习, Spring学习教程, Spring下载, Spring框架, Spring框架入门, Spring框架教程, Spring框架高级教程, Spring面试题, Spring笔试题, Spring编程思想