Spring oxm入門實(shí)例
O/XMapper是什么?
Spring3.0的一個(gè)新特性是O/XMapper。O/X映射器這個(gè)概念并不新鮮,O代表Object,X代表XML。它的目的是在Java對(duì)象(幾乎總是一個(gè)plainoldJavaobject,或簡(jiǎn)寫為POJO)和XML文檔之間來回轉(zhuǎn)換。
例如,您可能有一個(gè)帶有幾個(gè)屬性的簡(jiǎn)單bean,且您的業(yè)務(wù)需要將那個(gè)Java對(duì)象轉(zhuǎn)換為一個(gè)XML文檔。Spring的O/XMapper能夠?yàn)槟鉀Q那個(gè)問題。如果反過來,您需要將一個(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之間來回轉(zhuǎn)換的實(shí)用程序。Castor就是這樣一個(gè)流行的第三方工具,本文將使用這個(gè)工具。其他這樣的工具包括XMLBeans、JavaArchitectureforXMLBinding(JAXB)、JiBX和XStream。
編組和解組
進(jìn)行O/X映射時(shí),您經(jīng)常會(huì)看到編組(marshalling)和解組(unmarshalling)這兩個(gè)術(shù)語。
編組指將Javabean轉(zhuǎn)換成XML文檔的過程,這意味著Javabean的所有字段和字段值都將作為XML元素或?qū)傩蕴畛涞絏ML文件中。有時(shí),編組也稱為序列化(serializing)。
如您所料,解組是與編組完全相反的過程,即將XML文檔轉(zhuǎn)換為Javabean,這意味著XML文檔的所有元素或?qū)傩远甲鳛镴ava字段填充到Javabean中。有時(shí),解組也稱為反序列化(deserializing)。
使用Spring的O/XMapper的好處
使用Spring的O/XMapper的一個(gè)最直接的好處是可以通過利用Spring框架的其他特性簡(jiǎn)化配置。Spring的bean庫支持將實(shí)例化的O/X編組器注入(即前面提到過的“依賴項(xiàng)注入”)使用那些編組器的對(duì)象。重申一遍,這將加快應(yīng)用程序開發(fā)和部署。
遵循堅(jiān)實(shí)的面向?qū)ο蟮脑O(shè)計(jì)實(shí)踐,SpringO/X框架只定義兩個(gè)接口:Marshaller和Unmarshaller,它們用于執(zhí)行O/X功能,這是使用這個(gè)框架的另一個(gè)重大好處。這些接口的實(shí)現(xiàn)完全對(duì)獨(dú)立開發(fā)人員開放,開發(fā)人員可以輕松切換它們而無需修改代碼。例如,如果您一開始使用Castor進(jìn)行O/X轉(zhuǎn)換,但后來發(fā)現(xiàn)它缺乏您需要的某個(gè)功能,這時(shí)您可以切換到XMLBeans而無需任何代碼更改。唯一需要做的就是更改Spring配置文件以使用新的O/X框架。
使用Spring的O/XMapper的另一個(gè)好處是統(tǒng)一的異常層次結(jié)構(gòu)。Spring框架遵循使用它的數(shù)據(jù)訪問模塊建立的模式,方法是將原始異常對(duì)象包裝到Spring自身專為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。
入門栗子
配置清單:
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才能成功(這里存在疑問,不知道是否因?yàn)樽约簩懛▎栴},只能通過mapping進(jìn)行格式編碼才能進(jìn)行解組,否則報(bào)出無法找到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入門實(shí)例的全部?jī)?nèi)容,希望對(duì)大家有所幫助。感興趣的朋友可以繼續(xù)參閱本站其他相關(guān)專題,如有不足之處,歡迎留言指出。感謝朋友們對(duì)本站的支持!
相關(guān)文章
spring和quartz整合,并簡(jiǎn)單調(diào)用(實(shí)例講解)
下面小編就為大家?guī)硪黄猻pring和quartz整合,并簡(jiǎn)單調(diào)用(實(shí)例講解)。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2017-07-07
springboot中項(xiàng)目啟動(dòng)時(shí)實(shí)現(xiàn)初始化方法加載參數(shù)
這篇文章主要介紹了springboot中項(xiàng)目啟動(dòng)時(shí)實(shí)現(xiàn)初始化方法加載參數(shù),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-12-12
記一次用IDEA打開java項(xiàng)目后不能運(yùn)行的解決方法
這篇文章主要介紹了記一次用IDEA打開java項(xiàng)目后不能運(yùn)行的解決方法,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-03-03
Java Socket編程(四) 重復(fù)和并發(fā)服務(wù)器
Java Socket編程(四) 重復(fù)和并發(fā)服務(wù)器...2006-12-12
解決后端傳long類型數(shù)據(jù)到前端精度丟失問題
這篇文章主要介紹了解決后端傳long類型數(shù)據(jù)到前端精度丟失問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-01-01
Shiro整合Springboot和redis,jwt過程中的錯(cuò)誤shiroFilterChainDefinition問
這篇文章主要介紹了Shiro整合Springboot和redis,jwt過程中的錯(cuò)誤shiroFilterChainDefinition問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-04-04
Mybatis/Mybatis-Plus駝峰式命名映射的實(shí)現(xiàn)
本文主要介紹了Mybatis-Plus駝峰式命名映射的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-07-07

