مشخصات مقاله
آموزش انتقال شی به XML بوسیله جریان در Java Spring
Spring با Xstream
مثال Spring با Xstream
Xstream یک کتابخانه برای سریال کردن اشیا به xml و بالعکس، بدون نیاز به نگاشت هیچ فایلی است. توجه داشته باشید، castor نیاز به فایل نگاشت دارد. کلاس XStreamMarshaller تسهیلاتی برای انتقال اشیا به xml و بالعکس ارائه می دهد.
مثال ادغام Spring و Xstream (انتقال شی جاوا به xml)
فایل های زیر را برای انتقال شی جاوا به xml با استفاده از Spring و Xstream ایجاد می کنیم:
- Employee.java
- applicationContext.xml
- Client.java
فایل های jar مورد نیاز :
برای اجرای این مثال باید فایل های jar هسته Spring ، Web Springو xstream-1.3.jar را بارگذاری کنید.
Employee.java :
سه خصیصه شناسه، نام و حقوق را به همراه getter و setter ها تعریف می کند.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | package com.javatpoint; 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; } } <button></button> |
applicationContext.xml :
Bean، xstreamMarshallerBean را تعریف می کند به طوری که کلاس Employee محدود به فریمورک OXM شود.
1 2 3 4 5 6 7 8 9 10 11 12 | < ? xml version = "1.0" encoding = "UTF-8" ?> 4. xsi:schemaLocation="http://www.springframework.org/schema/beans < bean id = "xstreamMarshallerBean" class = "org.springframework.oxm.xstream.XStreamMarshaller" > < property name = "annotatedClasses" value = "com.javatpoint.Employee" >< / property > < / bean > < / beans > < button ></ button > |
Client.java :
از فایل applicationContext.xml یک نمونه از Marshaller می گیرد و متد marshal را فراخوانی می کند.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | package com.javatpoint; 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" ); } } <button></button> |
خروجی مثال :
employee.xml
1 2 3 4 5 6 | < com.javatpoint.Employee> < id> 101 < /id> < name>Sonoo Jaiswal< /name> < salary> 100000.0 < /salary> < /com.javatpoint.Employee> <button></button> |