当前位置: 移动技术网 > IT编程>开发语言>Java > Spring oxm入门实例

Spring oxm入门实例

2019年07月19日  | 移动技术网IT编程  | 我要评论

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

测试结果:

五月 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入门实例的全部内容,希望对大家有所帮助。感兴趣的朋友可以继续参阅本站其他相关专题,如有不足之处,欢迎留言指出。感谢朋友们对本站的支持!

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网