国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁(yè) > 開(kāi)發(fā) > Java > 正文

Spring oxm入門(mén)實(shí)例

2024-07-13 10:15:35
字體:
來(lái)源:轉(zhuǎn)載
供稿:網(wǎng)友

O/XMapper是什么?

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

例如,您可能有一個(gè)帶有幾個(gè)屬性的簡(jiǎn)單bean,且您的業(yè)務(wù)需要將那個(gè)Java對(duì)象轉(zhuǎn)換為一個(gè)XML文檔。Spring的O/XMapper能夠?yàn)槟鉀Q那個(gè)問(wèn)題。如果反過(guò)來(lái),您需要將一個(gè)XML文檔轉(zhuǎn)換為一個(gè)簡(jiǎn)單Javabean,Spring的O/XMapper也能勝任。

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

編組和解組

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

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

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

使用Spring的O/XMapper的好處

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

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

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

入門(mén)栗子

配置清單:

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> 

編組和解組時(shí),套用的mapping格式,在進(jìn)行解組的時(shí)候,必須使用mapping才能成功(這里存在疑問(wèn),不知道是否因?yàn)樽约簩?xiě)法問(wèn)題,只能通過(guò)mapping進(jìn)行格式編碼才能進(jìn)行解組,否則報(bào)出無(wú)法找到rootelement的錯(cuò)誤)。

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();			}		}	}}

測(cè)試

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");	}}

測(cè)試結(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 

總結(jié)

以上就是本文關(guān)于Spring oxm入門(mén)實(shí)例的全部?jī)?nèi)容,希望對(duì)大家有所幫助。感興趣的朋友可以繼續(xù)參閱本站其他相關(guān)專(zhuān)題,如有不足之處,歡迎留言指出。感謝朋友們對(duì)本站的支持!


注:相關(guān)教程知識(shí)閱讀請(qǐng)移步到JAVA教程頻道。
發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 麻江县| 河北区| 班戈县| 漳州市| 永昌县| 鸡东县| 肃南| 巴林左旗| 阿瓦提县| 信宜市| 九龙县| 朔州市| 依兰县| 萝北县| 清原| 吴堡县| 孟州市| 苏尼特左旗| 库尔勒市| 麻城市| 梨树县| 黎平县| 疏勒县| 大余县| 台江县| 东乡族自治县| 安溪县| 浮梁县| 阳东县| 仁寿县| 府谷县| 平定县| 崇仁县| 梨树县| 天津市| 青川县| 锡林浩特市| 喀喇| 河东区| 茂名市| 柞水县|