What is O/XMapper?
A new feature of Spring 3.0 is O/XMapper. The concept of O/X mapper is not new. O represents Object and X represents XML. Its purpose is to convert back and forth between Java objects (almost always a plainoldJavaobject, or abbreviated as POJO) and XML documents.
For example, you might have a simple bean with several attributes, and your business needs to convert that Java object into an XML document. Spring's O/XMapper can solve that problem for you. If in turn, you need to convert an XML document into a simple Javabean, Spring's O/XMapper is also competent.
One thing to note: SpringO/XMapper is just a unified interface implemented by popular third-party frameworks. To take advantage of Spring's O/X functionality, you need a utility that converts back and forth between Java objects and XML. Castor is such a popular third-party tool, and this article will use this tool. Other such tools include XMLBeans, Java Architecture for XMLBinding (JAXB), JiBX and XStream.
Marshalling and union
When doing O/X mapping, you often see the terms marshalling and unmarshalling.
Marshalling refers to the process of converting a Javabean into an XML document, which means that all fields and field values of a Javabean will be populated into the XML file as XML elements or attributes. Sometimes, marshalling is also called serializing.
As you might expect, unmarshalling is the exact opposite process of marshalling, which is to convert an XML document to a Javabean, which means that all elements or attributes of the XML document are populated into the Javabean as Java fields. Sometimes, unmarshalling is also called deserializing.
Benefits of using Spring's O/XMapper
One of the most direct benefits of using Spring's O/XMapper is that configuration can be simplified by leveraging other features of the Spring framework. Spring's bean library supports the use of objects that use instantiated O/X marshaller injection (i.e. "Dependency Injection" mentioned earlier). Reiterate that this will speed up application development and deployment.
Following solid object-oriented design practices, the SpringO/X framework defines only two interfaces: Marshaller and Unmarshaller, which are used to perform O/X functions, which is another significant benefit of using this framework. The implementation of these interfaces is completely open to independent developers, and developers can easily switch them without modifying the code. For example, if you start with Castor for O/X conversion, but then find that it lacks some functionality you need, at this point you can switch to XMLBeans without any code changes. The only thing you need to do is change the Spring configuration file to use the new O/X framework.
Another benefit of using Spring's O/XMapper is the unified exception hierarchy. The Spring framework follows the pattern established by using its data access module by wrapping the original exception object into a runtime exception created by Spring itself for O/XMapper. Since the original exception thrown by a third-party provider is wrapped into the Spring runtime exception, you can find out the root cause of the exception. You don't have to bother modifying the code to catch the exception, as the exception is wrapped into a runtime exception. The following runtime exceptions extend the underlying exception XMLMappingException: GenericMarshallingFailureException, ValidationFailureException, MarshallingFailureException, and UnmarshallingFailureException.
Getting started with sir
Configuration list:
applicationContext.xmlSpring configuration file
<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> <!-- Introducing castor package:castor-1.3.2-core.jar,castor-1.3.2-xml.jar --> <bean id="castorMarshaller"> <property name="mappingLocation" value="classpath:mapping.xml" /> </bean> </beans>
When marshalling and ungrouping, the mapping format applied must be used to succeed when ungrouping (there is a question here. I don’t know if it can only be formatted through mapping to ungroup because of my own writing problem, otherwise an error that the rootelement cannot be found will be reported).
mapping.xml file
<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>
Customize bean files
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 file
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 getUnmarshal().unmarshal(new StreamSource(is));} finally {if (is != null) {is.close();}}}}test
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");}}Test results:
May 11, 2016 2:27:52 pm org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh information: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@1221be2: startup date [Wed May 11 14:27:51 CST 2016]; root of context hierarchy May 11, 2016 2:27:52 pm org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions Information: Loading XML bean definitions from class path resource [applicationContext.xml] May 11, 2016 2:27:52 pm org.springframework.oxm.castor.CastorMarshaller afterPropertiesSet Information: Configured using [class path resource [mapping.xml]] Convert Object to XML! Done Convert XML back to Object! com.mdf.springoxm.Customer@b419da Done
Summarize
The above is all about the Spring oxm entry example in this article, I hope it will be helpful to everyone. Interested friends can continue to refer to other related topics on this site. If there are any shortcomings, please leave a message to point it out. Thank you friends for your support for this site!