🚀 Master Spring OXM & XML Frameworks!
Subscribe to Ram N Java for clean Java tutorials, Spring framework integrations, and step-by-step code demonstrations!
🔔 Subscribe to Ram N JavaWhat Is Spring OXM and Castor?
In enterprise Java systems, converting Java objects to XML (and vice versa) is a common requirement for integrations, messaging, and web services. Spring OXM (Object/XML Mapping) provides a clean abstraction layer over popular XML binding frameworks. Among these, the Castor XML Binding Framework is an efficient, battle-tested tool that allows developers to map complex Java objects into structured XML documents seamlessly using modern Java annotation configuration.
Marshalling vs Unmarshalling Explained
- Marshalling (Serialization): The process of converting an in-memory Java object into an XML representation (such as writing to an XML file, stream, or HTTP payload).
- Unmarshalling (Deserialization): The reverse process, taking raw XML input and converting it back into a fully populated Java object graph.
- CastorMarshaller: Spring's dedicated bean that implements both the
MarshallerandUnmarshallerinterfaces, acting as the bridge to Castor's engine.
Key Steps for Annotation-Based Configuration
- Define Java Configuration (
@Configuration): Create an application configuration class marked with@Configurationand@ComponentScanto eliminate legacy XML configuration files. - Configure the CastorMarshaller Bean: Declare a
@Beanmethod returningCastorMarshallerand set the mapping file resource location if custom schema mapping is required. - Implement the Converter Service: Inject Spring's
MarshallerandUnmarshallerinto your service bean to execute transformations usingmarshal(Object, Result)andunmarshal(Source). - Execute via ApplicationContext: Bootstrap the container using
AnnotationConfigApplicationContextto perform conversions effortlessly at runtime.
Why Use Spring with Castor?
- Clean Abstraction: Spring wraps vendor-specific checked exceptions into runtime data-access exceptions, reducing boilerplate try-catch logic.
- Modern Java Config: Utilizing pure Java annotations makes your application easier to maintain, refactor, and test.
- Flexible Integration: Seamlessly integrate XML processing with Spring Boot, Spring Batch, or Spring Integration pipelines.
Recommended Next Videos
Expand your knowledge of Spring Object/XML Mapping with these related tutorials from our channel:
Click here to watch on Youtube:
https://www.youtube.com/watch?v=rBTXKdYAxHQ&list=UUhwKlOVR041tngjerWxVccw
Click the below Image to Enlarge:
| XML Marshalling and UnMarshalling using Spring and Castor XML binding framework - Annotation Config |
| XML Marshalling and UnMarshalling using Spring and Castor XML binding framework - Annotation Config |
| XML Marshalling and UnMarshalling using Spring and Castor XML binding framework - Annotation Config |
| XML Marshalling and UnMarshalling using Spring and Castor XML binding framework - Annotation Config |
| XML Marshalling and UnMarshalling using Spring and Castor XML binding framework - Annotation Config |
| XML Marshalling and UnMarshalling using Spring and Castor XML binding framework - Annotation Config |
| XML Marshalling and UnMarshalling using Spring and Castor XML binding framework - Annotation Config |
| XML Marshalling and UnMarshalling using Spring and Castor XML binding framework - Annotation Config |
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.ram.core</groupId>
<artifactId>SpringDemo</artifactId>
<packaging>jar</packaging>
<version>1.0-SNAPSHOT</version>
<name>SpringDemo</name>
<url>http://maven.apache.org</url>
<properties>
<spring.version>5.1.1.RELEASE</spring.version>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.8.2</version>
<scope>test</scope>
</dependency>
<!-- Spring 3 dependencies -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-oxm</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- Uses Castor for XML -->
<dependency>
<groupId>org.codehaus.castor</groupId>
<artifactId>castor</artifactId>
<version>1.2</version>
</dependency>
<!-- Castor need this -->
<dependency>
<groupId>xerces</groupId>
<artifactId>xercesImpl</artifactId>
<version>2.8.1</version>
</dependency>
</dependencies>
</project>
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.ram.core</groupId>
<artifactId>SpringDemo</artifactId>
<packaging>jar</packaging>
<version>1.0-SNAPSHOT</version>
<name>SpringDemo</name>
<url>http://maven.apache.org</url>
<properties>
<spring.version>5.1.1.RELEASE</spring.version>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.8.2</version>
<scope>test</scope>
</dependency>
<!-- Spring 3 dependencies -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-oxm</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- Uses Castor for XML -->
<dependency>
<groupId>org.codehaus.castor</groupId>
<artifactId>castor</artifactId>
<version>1.2</version>
</dependency>
<!-- Castor need this -->
<dependency>
<groupId>xerces</groupId>
<artifactId>xercesImpl</artifactId>
<version>2.8.1</version>
</dependency>
</dependencies>
</project>
Customer.java
package com.ram.core.model;
public class Customer
{
private String name;
private int age;
private String address;
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public int getAge()
{
return age;
}
public void setAge(int age)
{
this.age = age;
}
public String getAddress()
{
return address;
}
public void setAddress(String address)
{
this.address = address;
}
@Override
public String toString()
{
return "Customer [name=" + name + ", age=" + age
+ ", address=" + address + "]";
}
}
public class Customer
{
private String name;
private int age;
private String address;
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public int getAge()
{
return age;
}
public void setAge(int age)
{
this.age = age;
}
public String getAddress()
{
return address;
}
public void setAddress(String address)
{
this.address = address;
}
@Override
public String toString()
{
return "Customer [name=" + name + ", age=" + age
+ ", address=" + address + "]";
}
}
customer_mapping.xml
<mapping>
<class name="com.ram.core.model.Customer">
<map-to xml="customer" />
<field name="name" type="string">
<bind-xml name="name" node="element" />
</field>
<field name="age" type="integer">
<bind-xml name="age" node="attribute" />
</field>
<field name="address" type="string">
<bind-xml name="address" node="element" />
</field>
</class>
</mapping>
<class name="com.ram.core.model.Customer">
<map-to xml="customer" />
<field name="name" type="string">
<bind-xml name="name" node="element" />
</field>
<field name="age" type="integer">
<bind-xml name="age" node="attribute" />
</field>
<field name="address" type="string">
<bind-xml name="address" node="element" />
</field>
</class>
</mapping>
XMLConverter.java
package com.ram.core;
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 XMLConverter
{
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 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 XMLConverter
{
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();
}
}
}
}
AppConfig.java
package com.ram.core.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.oxm.castor.CastorMarshaller;
import com.ram.core.XMLConverter;
@Configuration
public class AppConfig
{
@Bean
public XMLConverter getHandler()
{
XMLConverter xmlConverter = new XMLConverter();
xmlConverter.setMarshaller(getCastorMarshaller());
xmlConverter.setUnmarshaller(getCastorMarshaller());
return xmlConverter;
}
@Bean
public CastorMarshaller getCastorMarshaller()
{
@SuppressWarnings("deprecation")
CastorMarshaller castorMarshaller = new CastorMarshaller();
Resource resource = new ClassPathResource(
"customer_mapping.xml");
castorMarshaller.setMappingLocation(resource);
return castorMarshaller;
}
}
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.oxm.castor.CastorMarshaller;
import com.ram.core.XMLConverter;
@Configuration
public class AppConfig
{
@Bean
public XMLConverter getHandler()
{
XMLConverter xmlConverter = new XMLConverter();
xmlConverter.setMarshaller(getCastorMarshaller());
xmlConverter.setUnmarshaller(getCastorMarshaller());
return xmlConverter;
}
@Bean
public CastorMarshaller getCastorMarshaller()
{
@SuppressWarnings("deprecation")
CastorMarshaller castorMarshaller = new CastorMarshaller();
Resource resource = new ClassPathResource(
"customer_mapping.xml");
castorMarshaller.setMappingLocation(resource);
return castorMarshaller;
}
}
castor.properties
org.exolab.castor.indent = true
App.java
package com.ram.core;
import java.io.IOException;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import com.ram.core.config.AppConfig;
import com.ram.core.model.Customer;
public class App
{
private static final String XML_FILE_NAME = "customer.xml";
public static void main(String[] args) throws IOException
{
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(
AppConfig.class);
XMLConverter converter = (XMLConverter) context
.getBean(XMLConverter.class);
Customer customer = new Customer();
customer.setName("Peter");
customer.setAge(52);
customer.setAddress("A505,North Street,Bangalore");
// from object to XML file
converter.convertFromObjectToXML(customer, XML_FILE_NAME);
System.out.println("Converted Object to XML!");
// from XML to object
Customer customer2 = (Customer) converter
.convertFromXMLToObject(XML_FILE_NAME);
System.out.println(customer2);
System.out.println("Converted XML to Object!");
}
}
import java.io.IOException;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import com.ram.core.config.AppConfig;
import com.ram.core.model.Customer;
public class App
{
private static final String XML_FILE_NAME = "customer.xml";
public static void main(String[] args) throws IOException
{
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(
AppConfig.class);
XMLConverter converter = (XMLConverter) context
.getBean(XMLConverter.class);
Customer customer = new Customer();
customer.setName("Peter");
customer.setAge(52);
customer.setAddress("A505,North Street,Bangalore");
// from object to XML file
converter.convertFromObjectToXML(customer, XML_FILE_NAME);
System.out.println("Converted Object to XML!");
// from XML to object
Customer customer2 = (Customer) converter
.convertFromXMLToObject(XML_FILE_NAME);
System.out.println(customer2);
System.out.println("Converted XML to Object!");
}
}
Output:
Converted Object to XML!
Customer [name=Peter, age=52, address=A505,North Street,Bangalore]
Converted XML to Object!
Customer [name=Peter, age=52, address=A505,North Street,Bangalore]
Converted XML to Object!
customer.xml
<?xml version="1.0" encoding="UTF-8"?>
<customer age="52">
<name>Peter</name>
<address>A505,North Street,Bangalore</address>
</customer>
<customer age="52">
<name>Peter</name>
<address>A505,North Street,Bangalore</address>
</customer>
Click the below link to download the code:
https://sites.google.com/site/javaspringram2019/java_spring_2019/SpringDemo_Object_XML_mapping_castor_Annotation_config.zip?attredirects=0&d=1
Github Link:
https://github.com/ramram43210/Java_Spring_2019/tree/master/Spring_2019/SpringDemo_Object_XML_mapping_castor_Annotation_config
Bitbucket Link:
https://bitbucket.org/ramram43210/java_spring_2019/src/c049acad029f0a80d06bdf2c723a2d5703cecc59/Spring_2019/SpringDemo_Object_XML_mapping_castor_Annotation_config/?at=master
See also:
No comments:
Post a Comment