JAXB
Spring RestTemplate
Java
XML
Annotations

How do I use JAXB annotations with Spring RestTemplate?

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

If a Spring client has to send or receive XML, JAXB annotations give you a clean way to map Java classes to that XML structure. RestTemplate can then serialize and deserialize those classes through an XML message converter. The key is to annotate the model correctly and make sure the template has a converter that understands JAXB-bound objects.

Annotate the Model for XML

JAXB works by reading annotations on a Java class and turning that class into XML, or the reverse. A small model class with a root element and field mappings is enough for many APIs.

java
1import jakarta.xml.bind.annotation.XmlAccessType;
2import jakarta.xml.bind.annotation.XmlAccessorType;
3import jakarta.xml.bind.annotation.XmlElement;
4import jakarta.xml.bind.annotation.XmlRootElement;
5
6@XmlRootElement(name = "customer")
7@XmlAccessorType(XmlAccessType.FIELD)
8public class Customer {
9
10    @XmlElement(name = "id")
11    private long id;
12
13    @XmlElement(name = "name")
14    private String name;
15
16    public Customer() {
17    }
18
19    public Customer(long id, String name) {
20        this.id = id;
21        this.name = name;
22    }
23
24    public long getId() {
25        return id;
26    }
27
28    public String getName() {
29        return name;
30    }
31}

@XmlRootElement defines the top-level XML element. @XmlAccessorType(XmlAccessType.FIELD) tells JAXB to bind the fields directly, which is usually simpler than annotating every getter.

Configure RestTemplate for XML

Spring needs an HTTP message converter that can turn a JAXB-annotated class into XML and parse XML back into that class. The usual choice is Jaxb2RootElementHttpMessageConverter.

java
1import java.util.List;
2import org.springframework.http.converter.HttpMessageConverter;
3import org.springframework.http.converter.xml.Jaxb2RootElementHttpMessageConverter;
4import org.springframework.web.client.RestTemplate;
5
6public class RestTemplateFactory {
7    public static RestTemplate createXmlTemplate() {
8        RestTemplate restTemplate = new RestTemplate();
9        List<HttpMessageConverter<?>> converters = restTemplate.getMessageConverters();
10        converters.add(new Jaxb2RootElementHttpMessageConverter());
11        return restTemplate;
12    }
13}

In many Spring applications the converter is already present, but it is worth checking explicitly if XML mapping is failing. If the converter is missing, RestTemplate will not know how to handle the JAXB class.

Send XML Requests

Once the model and converter are in place, you can post a JAXB-annotated object just like any other request body. Set the content type to application/xml so the server sees the intended format.

java
1import org.springframework.http.HttpEntity;
2import org.springframework.http.HttpHeaders;
3import org.springframework.http.MediaType;
4import org.springframework.http.ResponseEntity;
5import org.springframework.web.client.RestTemplate;
6
7public class XmlClient {
8    public static void main(String[] args) {
9        RestTemplate restTemplate = RestTemplateFactory.createXmlTemplate();
10
11        Customer customer = new Customer(101, "Ava");
12
13        HttpHeaders headers = new HttpHeaders();
14        headers.setContentType(MediaType.APPLICATION_XML);
15        headers.setAccept(List.of(MediaType.APPLICATION_XML));
16
17        HttpEntity<Customer> request = new HttpEntity<>(customer, headers);
18
19        ResponseEntity<Customer> response = restTemplate.postForEntity(
20            "https://example.com/api/customers",
21            request,
22            Customer.class
23        );
24
25        System.out.println(response.getBody().getName());
26    }
27}

The same mechanism works for put, exchange, and other RestTemplate methods. The converter handles the XML transformation.

Read XML Responses

For simple GET operations, the code is even smaller. If the server responds with XML that matches the JAXB model, RestTemplate will build the Java object directly.

java
1RestTemplate restTemplate = RestTemplateFactory.createXmlTemplate();
2Customer customer = restTemplate.getForObject(
3    "https://example.com/api/customers/101",
4    Customer.class
5);
6
7System.out.println(customer.getName());

If the XML shape does not match the class structure, deserialization will fail. In that case, the model annotations usually need adjustment rather than changes to the request code.

Handle Collections and Nested Elements

Real XML payloads often contain nested objects or repeated elements. JAXB supports that with @XmlElementWrapper, @XmlElement, and nested annotated classes. The important rule is that the Java structure should mirror the XML structure closely. If the XML uses wrapper elements, your model usually should as well.

It is also common to add a no-argument constructor because JAXB needs one for deserialization.

Know the Limits

RestTemplate is still widely used, but Spring now treats it as a mature synchronous client rather than the preferred path for new reactive workloads. That does not affect JAXB usage directly, but it does mean XML client code should stay simple and explicit. If the service contract is XML and synchronous, RestTemplate with JAXB is still a practical solution.

Common Pitfalls

  • Forgetting @XmlRootElement and then wondering why the converter cannot marshal the class.
  • Missing a no-argument constructor required for JAXB deserialization.
  • Failing to register an XML message converter with RestTemplate.
  • Sending XML without setting Content-Type and Accept headers appropriately.
  • Modeling nested XML loosely so the Java class no longer matches the payload shape.

Summary

  • Use JAXB annotations to map Java classes directly to XML.
  • 'RestTemplate needs a JAXB-aware message converter to serialize and deserialize those classes.'
  • '@XmlRootElement and a no-argument constructor are usually required.'
  • Set XML headers explicitly when making requests.
  • If parsing fails, inspect the Java model first because the XML shape and class structure must match.

Related reading
Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.