Spring oxm入门实例
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入门实例的全部内容,希望对大家有所帮助。感兴趣的朋友可以继续参阅本站其他相关专题,如有不足之处,欢迎留言指出。感谢朋友们对本站的支持!
您可能感兴趣的文章:
- Spring自动装配与扫描注解代码详解
- Spring MVC参数传递中文乱码解决方法分享
- springmvc和js前端的数据传递和接收方式(两种)
- spring security自定义认证登录的全过程记录
- 详解Springboot事务管理
- spring mvc实现文件上传与下载功能
- spring Boot打包部署到远程服务器的tomcat中
- SpringBoot 监控管理模块actuator没有权限的问题解决方法
Spring oxm入门实例的更多相关文章
- Eclipse安装springsource-tool-suite插件及spring helloworld入门实例
转载至: https://www.cnblogs.com/aaron-shu/p/5156007.html 一.查看eclipse版本 Help-->About Eclipse,我的版本是4.4 ...
- Spring Boot下Spring Batch入门实例
一.About Spring Batch是什么能干什么,网上一搜就有,但是就是没有入门实例,能找到的例子也都是2.0的,看文档都是英文无从下手~~~,使用当前最新的版本整合网络上找到的例子. 关于基础 ...
- spring oxm入门(包含demo)
O/X Mapper 是什么? Spring 3.0 的一个新特性是 O/X Mapper.O/X 映射器这个概念并不新鲜,O 代表 Object,X 代表 XML.它的目的是在 Java 对象(几乎 ...
- Spring AOP 入门实例详解
目录 AOP概念 AOP核心概念 Spring对AOP的支持 基于Spring的AOP简单实现 基于Spring的AOP使用其他细节 AOP概念 AOP(Aspect Oriented Program ...
- Spring Boot入门实例
简介 Spring Boot是由Pivotal团队提供的全新框架,其设计目的是用来简化新Spring应用的初始搭建以及开发过程.该框架使用了特定的方式来进行配置,从而使开发人员不再需要定义样板化的配置 ...
- Spring 简单入门实例
首先新建一个Web 项目 导入相应Jar 包 <?xml version="1.0" encoding="UTF-8"?> <beans xm ...
- 建立spring项目入门实例
建立maven项目 打开pop.xml文件 添加springframework所依赖的包 <!-- https://mvnrepository.com/artifact/org.springfr ...
- Spring MVC 入门实例报错404的解决方案
若启动服务器控制台报错,并且是未找到xml配置文件,初始化DispatchServlet失败,或者控制台未报错404,那么: 1.URL的排查: 格式-----------协议名://地址:端口号/上 ...
- Spring MVC入门实例
1.web.xml配置 <?xml version="1.0" encoding="UTF-8"? > <web-app xmlns:xsi= ...
随机推荐
- VS2013 tips
1.创建一个connection时会自动产生一个localdb数据库文件,可以通过Server Explorer窗口查看这个localDB,注意,是Server Explorer窗口,而不是SQL S ...
- windows主机与virtualbox虚拟机下的Linux共享网络
环境: 主机:windows7 虚拟机:virtualbox 4.2 虚拟系统:CentOS6.2 需求: 1.虚拟机linux可以共享主机网络上互联网 2.主机.虚拟机互通讯,组成一个虚拟的局域网, ...
- BZOJ4976:宝石镶嵌(DP&思维)
Description 魔法师小Q拥有n个宝石,每个宝石的魔力依次为w_1,w_2,...,w_n.他想把这些宝石镶嵌到自己的法杖上,来提升 法杖的威力.不幸的是,小Q的法杖上宝石镶嵌栏太少了,他必须 ...
- test20190305
上午考试,是 \(SCOI\ 2016\ Day\ 1\) 的题目. 背单词 这题我以前是做过的.Trie树总结. #include<bits/stdc++.h> using namesp ...
- atom的设置
1.隐藏Keybinding Resolver Packages->Keybinding Resolver->Toggle.
- MYSQL在当前日期的基础上加上N(年月日分秒)
//把id为1的那条数据的开始时间改为现在 结束时间改为开始时间的1个月后 update 表明 set begintime=now(),endtime=date_add(NOW(), interv ...
- Linux驱动程序接口
§1. Linux驱动程序接口 系统调用是操作系统内核与应用程序之间的接口,设备驱动程序则是操作系统内核与机器硬件的接口.几乎所有的系统操作最终映射到物理设备,除了CPU.内存和少数其它设备,所有的设 ...
- MyEclipse项目突然报错JavanotFindClassException
版权声明:本文为博主原创文章,未经博主同意不得转载. https://blog.csdn.net/UP19910522/article/details/25985277 好好的项目.从SVN检出到本地 ...
- odoo 使用源码安装时的注意
odoo 使用源码安装时的注意 使用 odoo 源安装 odoo 时,会增加 odoo 官方的 odoo 源. 安装时直接输入 yum install odoo 即可安装 odoo. 但是更新时就要注 ...
- (转)Android自定义属性时format选项( <attr format="reference" name="background" /> )
Android自定义属性时format选项可以取用的值 1. reference:参考某一资源ID. (1)属性定义: [html] view plaincopyprint? <declar ...