O/XMapper是什麼?
Spring3.0的一個新特性是O/XMapper。 O/X映射器這個概念並不新鮮,O代表Object,X代表XML。它的目的是在Java對象(幾乎總是一個plainoldJavaobject,或簡寫為POJO)和XML文檔之間來迴轉換。
例如,您可能有一個帶有幾個屬性的簡單bean,且您的業務需要將那個Java對象轉換為一個XML文檔。 Spring的O/XMapper能夠為您解決那個問題。如果反過來,您需要將一個XML文檔轉換為一個簡單Javabean,Spring的O/XMapper也能勝任。
有一點需要注意:SpringO/XMapper只是定義由流行的第三方框架實現的統一的界面。要利用Spring的O/X功能,您需要一個在Java對象和XML之間來迴轉換的實用程序。 Castor就是這樣一個流行的第三方工具,本文將使用這個工具。其他這樣的工具包括XMLBeans、JavaArchitectureforXMLBinding(JAXB)、JiBX和XStream。
編組和解組
進行O/X映射時,您經常會看到編組(marshalling)和解組(unmarshalling)這兩個術語。
編組指將Javabean轉換成XML文檔的過程,這意味著Javabean的所有字段和字段值都將作為XML元素或屬性填充到XML文件中。有時,編組也稱為序列化(serializing)。
如您所料,解組是與編組完全相反的過程,即將XML文檔轉換為Javabean,這意味著XML文檔的所有元素或屬性都作為Java字段填充到Javabean中。有時,解組也稱為反序列化(deserializing)。
使用Spring的O/XMapper的好處
使用Spring的O/XMapper的一個最直接的好處是可以通過利用Spring框架的其他特性簡化配置。 Spring的bean庫支持將實例化的O/X編組器注入(即前面提到過的“依賴項注入”)使用那些編組器的對象。重申一遍,這將加快應用程序開發和部署。
遵循堅實的面向對象的設計實踐,SpringO/X框架只定義兩個接口:Marshaller和Unmarshaller,它們用於執行O/X功能,這是使用這個框架的另一個重大好處。這些接口的實現完全對獨立開發人員開放,開發人員可以輕鬆切換它們而無需修改代碼。例如,如果您一開始使用Castor進行O/X轉換,但後來發現它缺乏您需要的某個功能,這時您可以切換到XMLBeans而無需任何代碼更改。唯一需要做的就是更改Spring配置文件以使用新的O/X框架。
使用Spring的O/XMapper的另一個好處是統一的異常層次結構。 Spring框架遵循使用它的數據訪問模塊建立的模式,方法是將原始異常對象包裝到Spring自身專為O/XMapper建立的運行時異常中。由於第三方提供商拋出的原始異常被包裝到Spring運行時異常中,您能夠查明出現異常的根本原因。您也不必費心修改代碼以捕獲異常,因為異常已包裝到一個運行時異常中。以下幾個運行時異常擴展了基礎異常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"> <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"> <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");}}測試結果:
五月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入門實例的全部內容,希望對大家有所幫助。感興趣的朋友可以繼續參閱本站其他相關專題,如有不足之處,歡迎留言指出。感謝朋友們對本站的支持!