Home  >  Spring Core

Spring + JAXB Integration Annotation Pretty Print Example with Jaxb2Marshaller

By Arvind Rai, March 29, 2015
In this page we will learn Spring and JAXB Integration Annotation Pretty Print Example with Jaxb2Marshaller to convert XML to/from java object. Using Jaxb2Marshaller instance, we create the instance of Marshaller and Unmarshaller. For pretty printing we need to set jaxb.formatted.output property as true in Jaxb2Marshaller. For XML and Java object mapping, we need to create java bean with properties which is mapped with XML tags and attributes. Annotate properties with javax.xml.bind.annotation XmlAttribute and XmlElement etc that will map XML attribute and element with java bean properties.

Required Software

To run the application, we need following software.
1. Java 7
2. Gradle
3. Eclipse
4. Spring-Oxm:4.1.5.RELEASE

Gradle File for Spring OXM and Spring Boot Starter

Find the gradle file for spring OXM and spring Boot Starter.
build.xml
apply plugin: 'java'
apply plugin: 'eclipse'
archivesBaseName = 'concretepage'
version = '1' 
repositories {
    mavenCentral()
}
dependencies {
	compile 'org.springframework.boot:spring-boot-starter:1.2.2.RELEASE'
	compile 'org.springframework:spring-oxm:4.1.5.RELEASE'
}  

Annotation Based Configuration File for Jaxb2Marshaller and Pretty Print

Spring OXM provides Jaxb2Marshaller instance which is used to create instances of Marshaller and Unmarshaller. We can set properties in Jaxb2Marshaller for pretty printing, encoding etc of XML. To perform pretty printing, need to perform below steps.
map.put("jaxb.formatted.output", true);
jaxb2Marshaller.setMarshallerProperties(map); 
Find the configuration class now.
AppConfig.java
package com.concretepage;
import java.util.HashMap;
import java.util.Map;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.oxm.jaxb.Jaxb2Marshaller;
@Configuration
public class AppConfig {
	@Bean
	public Processor getHandler(){
	  Processor handler= new Processor();
	  handler.setMarshaller(getCastorMarshaller());
	  handler.setUnmarshaller(getCastorMarshaller());
	  return handler;
	}
	@Bean
	public Jaxb2Marshaller getCastorMarshaller() {
	  Jaxb2Marshaller jaxb2Marshaller = new Jaxb2Marshaller();
	  jaxb2Marshaller.setPackagesToScan("com.concretepage.bean");
	  Map<String,Object> map = new HashMap<String,Object>();
	  map.put("jaxb.formatted.output", true);
	  jaxb2Marshaller.setMarshallerProperties(map);
          return jaxb2Marshaller;
	}
} 

Bean for XML Mapping

For XML and Java object mapping, java provides different annotations like @XmlRootElement, @XmlAccessorType, @XmlAttribute and @XmlElement. To get java properties as XML attribute, use @XmlAttribute and for XML sub tag we need to use @XmlElement annotation on properties.
Company.java
package com.concretepage.bean;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name="company-info", namespace="com.concretepage" )
@XmlAccessorType(XmlAccessType.NONE)
public class Company {
	@XmlAttribute(name="id")
	private Integer id;
	@XmlElement(name="company-name")
	private String companyName;
	@XmlElement(name="ceo-name")
	private String ceoName;
	@XmlElement(name="no-emp")
	private Integer noEmp;
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getCompanyName() {
		return companyName;
	}
	public void setCompanyName(String companyName) {
		this.companyName = companyName;
	}
	public String getCeoName() {
		return ceoName;
	}
	public void setCeoName(String ceoName) {
		this.ceoName = ceoName;
	}
	public Integer getNoEmp() {
		return noEmp;
	}
	public void setNoEmp(Integer noEmp) {
		this.noEmp = noEmp;
	}
} 

Define Method for Marshaller and Unmarshaller

Now find a utility method in which we are calling Marshaller and Unmarshaller.
Processor.java
package com.concretepage;
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 Processor {
    private Marshaller marshaller;
    private Unmarshaller unmarshaller;

    public void setMarshaller(Marshaller marshaller) {
        this.marshaller = marshaller;
    }

    public void setUnmarshaller(Unmarshaller unmarshaller) {
        this.unmarshaller = unmarshaller;
    }
    //Converts Object to XML file
    public void objectToXML(String fileName, Object graph) throws IOException {
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(fileName);
            marshaller.marshal(graph, new StreamResult(fos));
        } finally {
        	fos.close();
        }
    }
    //Converts XML to Java Object
    public Object xmlToObject(String fileName) throws IOException {
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(fileName);
            return unmarshaller.unmarshal(new StreamSource(fis));
        } finally {
        	fis.close();
        }
    }
} 

Run Application

To test the application, we are creating an object of our bean and converting it into XML and again converting that XML into java object.
RunApplication.java
package com.concretepage;
import java.io.IOException;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import com.concretepage.bean.Company;
public class RunApplication {
	public static void main(String[] args) throws IOException {
	   AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
	   ctx.register(AppConfig.class);
	   ctx.refresh();
	   Processor processor = ctx.getBean(Processor.class);
	   //Perform Marshaling
	   Company company = new Company();
	   company.setId(100);
	   company.setCompanyName("XYZ");
	   company.setCeoName("ABCD");
	   company.setNoEmp(100);
	   processor.objectToXML("country.xml", company);
	   System.out.println("Marshaling performed");
	   //Perform UnMarshaling
	   company = (Company)processor.xmlToObject("country.xml");
	   System.out.println("After UnMarshaling Data is: id:"+ company.getId()+", CountryName:"+company.getCompanyName());
	}
} 
Output for java object to XML.
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<ns2:company-info xmlns:ns2="com.concretepage" id="100">
    <company-name>XYZ</company-name>
    <ceo-name>ABCD</ceo-name>
    <no-emp>100</no-emp>
</ns2:company-info> 
And output for XML to java object.
Marshaling performed
After UnMarshaling Data is: id:100, CountryName:XYZ 

Download Complete Source Code

POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS






©2019 concretepage.com | Privacy Policy | Contact Us