Spring with Xstream
Spring
with Xstream Example
1. Spring and Xstream Integration
2. Example of Spring and Xstream
Integration
Xstream is a library to
serialize objects to xml and vice-versa without requirement of any mapping
file. Notice that castor requires an mapping file.
XStreamMarshaller class
provides facility to marshal objects into xml and vice-versa.
Example
of Spring and Xstream Integration (Marshalling Java Object into XML)
You need to create following files
for marshalling java object into XML using Spring with Xstream:
1. Employee.java
2. applicationContext.xml
3. Client.java
Required Jar files
To run this example, you need to
load:
Spring Core jar files
Spring Web jar files
xstream-1.3.jar
Employee.java
If defines three properties id,
name and salary with setters and getters.
package com.smgc;
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
It defines a bean
xstreamMarshallerBean where Employee class is bound with the OXM framework.
<?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="com.smgc.Employee"></property>
</bean>
</beans>
Client.java
It
gets the instance of Marshaller from the applicationContext.xml file and calls
the marshal method.
package com.smgc;
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("Piyush
Patel");
employee.setSalary(100000);
marshaller.marshal(employee, new
StreamResult(new FileWriter("employee.xml")));
System.out.println("XML
Created Sucessfully");
}
}
Output
of the example
employee.xml
<com.smgc.Employee>
<id>101</id>
<name>Piyush
Patel</name>
<salary>100000.0</salary>
</com.smgc.Employee>
Comments
Post a Comment