Force the use JAXB with Spring Boot

Updated: 2023-12-07

The issue

In my case I was producing the sitemap.xml of this website and I had configured Jackson XML in my Spring Boot configuration.

The problem of the result was that by default Jackson add an empty namespace (xmlns="") for every node in the xml.

Google didn't like this value and refused to parse the xml. This is an old and open issue for Jackson.

GitHub link to the issue: https://github.com/FasterXML/jackson-dataformat-xml/issues/355

Jaxb is an alternative

Jaxb doesn't present this issue and I used it in the past How to generate a sitemap with Java.

In the pom.xml I have the Jaxb libraries:

<dependency> 
  <groupId>jakarta.xml.bind</groupId> 
  <artifactId>jakarta.xml.bind-api</artifactId> 
  <version>4.0.0</version> 
</dependency> 
<dependency> 
<groupId>com.sun.xml.bind</groupId> 
  <artifactId>jaxb-impl</artifactId> 
  <version>4.0.2</version> 
  <scope>runtime</scope> 
</dependency> 

Tell Spring Boot to use Jaxb

In Spring you can define which converter to use to produce a result, ex. XML, using HttpMessageConverters

In our case we want to define an additional converter:

public HttpMessageConverters(HttpMessageConverter<?>... additionalConverters) 

We ask Spring to add the Jaxb Message Converter

@Configuration 
public class XmlConfiguration { 
 
    @Bean 
    public HttpMessageConverters customConverters() { 
        HttpMessageConverter<?> additionalConverter = new Jaxb2RootElementHttpMessageConverter(); 
        return new HttpMessageConverters(additionalConverter); 
    } 
} 

With this change we use the JAXB converter that according to the documentation : This converter can read classes annotated with XmlRootElement and XmlType, and write classes annotated with XmlRootElement, or subclasses thereof.


WebApp built by Marco using SpringBoot 3.2.4 and Java 21, in a Server in Switzerland without 'Cloud'.