Spring中oxm入門的示例分析

這篇文章主要介紹了Spring中oxm入門的示例分析,具有一定借鑒價值,感興趣的朋友可以參考下,希望大家閱讀完這篇文章之后大有收獲,下面讓小編帶著大家一起了解一下。

公司主營業(yè)務(wù):成都做網(wǎng)站、成都網(wǎng)站制作、成都外貿(mào)網(wǎng)站建設(shè)、移動網(wǎng)站開發(fā)等業(yè)務(wù)。幫助企業(yè)客戶真正實現(xiàn)互聯(lián)網(wǎng)宣傳,提高企業(yè)的競爭能力。創(chuàng)新互聯(lián)建站是一支青春激揚、勤奮敬業(yè)、活力青春激揚、勤奮敬業(yè)、活力澎湃、和諧高效的團隊。公司秉承以“開放、自由、嚴謹、自律”為核心的企業(yè)文化,感謝他們對我們的高要求,感謝他們從不同領(lǐng)域給我們帶來的挑戰(zhàn),讓我們激情的團隊有機會用頭腦與智慧不斷的給客戶帶來驚喜。創(chuàng)新互聯(lián)建站推出鄄城免費做網(wǎng)站回饋大家。

O/XMapper是什么?

Spring3.0的一個新特性是O/XMapper。O/X映射器這個概念并不新鮮,O代表Object,X代表XML。它的目的是在Java對象(幾乎總是一個plainoldJavaobject,或簡寫為POJO)和XML文檔之間來回轉(zhuǎn)換。

例如,您可能有一個帶有幾個屬性的簡單bean,且您的業(yè)務(wù)需要將那個Java對象轉(zhuǎn)換為一個XML文檔。Spring的O/XMapper能夠為您解決那個問題。如果反過來,您需要將一個XML文檔轉(zhuǎn)換為一個簡單Javabean,Spring的O/XMapper也能勝任。

有一點需要注意:SpringO/XMapper只是定義由流行的第三方框架實現(xiàn)的統(tǒng)一的界面。要利用Spring的O/X功能,您需要一個在Java對象和XML之間來回轉(zhuǎn)換的實用程序。Castor就是這樣一個流行的第三方工具,本文將使用這個工具。其他這樣的工具包括XMLBeans、JavaArchitectureforXMLBinding(JAXB)、JiBX和XStream。

編組和解組

進行O/X映射時,您經(jīng)常會看到編組(marshalling)和解組(unmarshalling)這兩個術(shù)語。

編組指將Javabean轉(zhuǎn)換成XML文檔的過程,這意味著Javabean的所有字段和字段值都將作為XML元素或?qū)傩蕴畛涞絏ML文件中。有時,編組也稱為序列化(serializing)。

如您所料,解組是與編組完全相反的過程,即將XML文檔轉(zhuǎn)換為Javabean,這意味著XML文檔的所有元素或?qū)傩远甲鳛镴ava字段填充到Javabean中。有時,解組也稱為反序列化(deserializing)。

使用Spring的O/XMapper的好處

使用Spring的O/XMapper的一個最直接的好處是可以通過利用Spring框架的其他特性簡化配置。Spring的bean庫支持將實例化的O/X編組器注入(即前面提到過的“依賴項注入”)使用那些編組器的對象。重申一遍,這將加快應(yīng)用程序開發(fā)和部署。

遵循堅實的面向?qū)ο蟮脑O(shè)計實踐,SpringO/X框架只定義兩個接口:Marshaller和Unmarshaller,它們用于執(zhí)行O/X功能,這是使用這個框架的另一個重大好處。這些接口的實現(xiàn)完全對獨立開發(fā)人員開放,開發(fā)人員可以輕松切換它們而無需修改代碼。例如,如果您一開始使用Castor進行O/X轉(zhuǎn)換,但后來發(fā)現(xiàn)它缺乏您需要的某個功能,這時您可以切換到XMLBeans而無需任何代碼更改。唯一需要做的就是更改Spring配置文件以使用新的O/X框架。

使用Spring的O/XMapper的另一個好處是統(tǒng)一的異常層次結(jié)構(gòu)。Spring框架遵循使用它的數(shù)據(jù)訪問模塊建立的模式,方法是將原始異常對象包裝到Spring自身專為O/XMapper建立的運行時異常中。由于第三方提供商拋出的原始異常被包裝到Spring運行時異常中,您能夠查明出現(xiàn)異常的根本原因。您也不必費心修改代碼以捕獲異常,因為異常已包裝到一個運行時異常中。以下幾個運行時異常擴展了基礎(chǔ)異常XMLMappingException:GenericMarshallingFailureException、ValidationFailureException、MarshallingFailureException和UnmarshallingFailureException。

入門栗子

配置清單:

applicationContext.xmlSpring配置文件

<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="oxmDemo" class="com.mdf.springoxm.oxmDemo"> 
    <property name="marshaller" ref="castorMarshaller" /> 
    <property name="unmarshaller" ref="castorMarshaller" /> 
  </bean> 
  <!-- 引入castor包:castor-1.3.2-core.jar,castor-1.3.2-xml.jar --> 
  <bean id="castorMarshaller" class="org.springframework.oxm.castor.CastorMarshaller"> 
     <property name="mappingLocation" value="classpath:mapping.xml" /> 
  </bean> 
</beans>

編組和解組時,套用的mapping格式,在進行解組的時候,必須使用mapping才能成功(這里存在疑問,不知道是否因為自己寫法問題,只能通過mapping進行格式編碼才能進行解組,否則報出無法找到rootelement的錯誤)。

mapping.xml文件

<mapping> 
    <class name="com.mdf.springoxm.Customer"> 
  
      <map-to xml="Customer"/> 
  
      <field name="flag" type="boolean"> 
       <bind-xml name="flag" node="element"/> 
      </field> 
        
      <field name="name" type="string"> 
       <bind-xml name="name" node="element"/> 
      </field> 
  
      <field name="sex" type="string"> 
       <bind-xml name="sex" node="element"/> 
      </field> 
    </class> 
</mapping>

自定義Bean文件

Customer.java

package com.mdf.springoxm;
public class Customer {
	private String name;
	private String sex;
	private Boolean flag;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getSex() {
		return sex;
	}
	public void setSex(String sex) {
		this.sex = sex;
	}
	public Boolean getFlag() {
		return flag;
	}
	public void setFlag(Boolean flag) {
		this.flag = flag;
	}
}

xmlDemo.java文件

package com.mdf.springoxm;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import org.springframework.oxm.Marshaller;
import org.springframework.oxm.Unmarshaller;
public class oxmDemo{
	private Marshaller marshaller;
	private Unmarshaller unmarshaller;
	public Marshaller getMarshaller() {
		return marshaller;
	}
	public void setMarshaller(Marshaller marshaller) {
		this.marshaller = marshaller;
	}
	public Unmarshaller getUnmarshaller() {
		return unmarshaller;
	}
	public void setUnmarshaller(Unmarshaller unmarshaller) {
		this.unmarshaller = unmarshaller;
	}
	public void convertFromObjectToXML(Object object, String filepath) 
	    throws IOException {
		FileOutputStream os = null;
		try {
			os = new FileOutputStream(filepath);
			getMarshaller().marshal(object, new StreamResult(os));
		}
		finally {
			if (os != null) {
				os.close();
			}
		}
	}
	public Object convertFromXMLToObject(String xmlfile) throws IOException {
		FileInputStream is = null;
		try {
			is = new FileInputStream(xmlfile);
			return getUnmarshaller().unmarshal(new StreamSource(is));
		}
		finally {
			if (is != null) {
				is.close();
			}
		}
	}
}

測試

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.mdf.springoxm.Customer;
import com.mdf.springoxm.oxmDemo;
import java.io.IOException;
public class Main {
	private static final String XML_FILE_NAME = "customer.xml";
	public static void main(String[] args) throws IOException {
		ApplicationContext appContext = new ClassPathXmlApplicationContext("applicationContext.xml");
		oxmDemo converter = (oxmDemo) appContext.getBean("oxmDemo");
		Customer customer = new Customer();
		customer.setName("yiibai");
		customer.setFlag(true);
		customer.setSex("Haikou haidiandao");
		System.out.println("Convert Object to XML!");
		//from object to XML file 
		converter.convertFromObjectToXML(customer, XML_FILE_NAME);
		System.out.println("Done \n");
		System.out.println("Convert XML back to Object!");
		//from XML to object 
		Customer customer2 = (Customer)converter.convertFromXMLToObject(XML_FILE_NAME);
		System.out.println(customer2);
		System.out.println("Done");
	}
}

測試結(jié)果:

五月 11, 2016 2:27:52 下午 org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh 
信息: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@1221be2: startup date [Wed May 11 14:27:51 CST 2016]; root of context hierarchy 
五月 11, 2016 2:27:52 下午 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions 
信息: Loading XML bean definitions from class path resource [applicationContext.xml] 
五月 11, 2016 2:27:52 下午 org.springframework.oxm.castor.CastorMarshaller afterPropertiesSet 
信息: Configured using [class path resource [mapping.xml]] 
Convert Object to XML! 
Done  
 
Convert XML back to Object! 
com.mdf.springoxm.Customer@b419da 
Done

感謝你能夠認真閱讀完這篇文章,希望小編分享的“Spring中oxm入門的示例分析”這篇文章對大家有幫助,同時也希望大家多多支持創(chuàng)新互聯(lián),關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道,更多相關(guān)知識等著你來學習!

網(wǎng)頁名稱:Spring中oxm入門的示例分析
URL分享:http://www.muchs.cn/article6/phohig.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供ChatGPT、外貿(mào)網(wǎng)站建設(shè)、搜索引擎優(yōu)化、小程序開發(fā)、手機網(wǎng)站建設(shè)、用戶體驗

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)

手機網(wǎng)站建設(shè)