Configuring a custom HttpMessageConverter in SpringBoot

The HttpMessageConverter provides a convenient way to add and merge additional converters in a web application. In this tutorial we will learn how to specify an additional HttpMessageConverter and add it to the default ones.

Here is an example class, which provides as additional HtpMessageConverter the MarshallingHttpMessageConverter:

package com.example.testrest;

import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.context.annotation.*;
import org.springframework.http.converter.xml.MarshallingHttpMessageConverter;
import org.springframework.oxm.xstream.XStreamMarshaller;

public class MyConfiguration {
  public HttpMessageConverters customConverters() {
    MarshallingHttpMessageConverter xmlConverter = new MarshallingHttpMessageConverter();
    XStreamMarshaller xstream = new XStreamMarshaller();
    return new HttpMessageConverters(xmlConverter);

The MarshallingHttpMessageConverter uses as marshaller/unmarshaller the XStreamMarshaller. The XStreamMarshaller has the capability to convert from/to XML any Java class without adding annotations to it.

In our case, we will use it to marshall/unmarshall the following Java Bean class:

public class Customer {
  private int id;
  private String name;

  public Customer(int id, String name) {
    super(); = id; = name;

  public String getName() {
    return name;

  public void setName(String name) { = name;

  public int getId() {
    return id;

  public void setId(int id) { = id;

Here is out Controller class:

public class CustomerController {
  @Autowired CustomerRepository repository;

  @RequestMapping(value = "/list", method = RequestMethod.GET)
  public List<Customer> findAll() {
    return repository.getData();

  @RequestMapping(value = "/one/{id}", method = RequestMethod.GET)
  public Customer findOne(@PathVariable int id) {
    return repository.getData().get(id);

You can see the effect of the marshaller. When requesting the Customer list:

curl --header "Accept: application/xml" http://localhost:8080/list  

On the other hand, you can still request the list of Customer as JSON:

curl --header "Accept: application/json" http://localhost:8080/list [{"id":1,"name":"frank"},{"id":2,"name":"john"}]

Source code for this tutorial: