Render XML in a Micronaut Controller

Learn how to use Jackson to render XML in a Micronaut Controller.

Authors: Sergio del Amo

Micronaut Version: 4.6.3

1. Getting Started

In this guide, we will create a Micronaut application written in Java.

2. What you will need

To complete this guide, you will need the following:

3. Solution

We recommend that you follow the instructions in the next sections and create the application step by step. However, you can go right to the completed example.

4. Writing the Application

Create an application using the Micronaut Command Line Interface or with Micronaut Launch.

mn create-app example.micronaut.micronautguide \
    --features=jackson-databind,jackson-xml \
    --build=maven \
    --lang=java \
    --test=junit
If you don’t specify the --build argument, Gradle with the Kotlin DSL is used as the build tool.
If you don’t specify the --lang argument, Java is used as the language.
If you don’t specify the --test argument, JUnit is used for Java and Kotlin, and Spock is used for Groovy.

The previous command creates a Micronaut application with the default package example.micronaut in a directory named micronautguide.

If you use Micronaut Launch, select Micronaut Application as application type and add jackson-databind, and jackson-xml features.

If you have an existing Micronaut application and want to add the functionality described here, you can view the dependency and configuration changes from the specified features and apply those changes to your application.

4.1. Dependency

In this guide, to render XML, we use Micronaut Jackson XML. Add the following dependency:

pom.xml
<dependency>
    <groupId>io.micronaut.xml</groupId>
    <artifactId>micronaut-jackson-xml</artifactId>
    <scope>compile</scope>
</dependency>
Micronaut Serialization doesn’t currently support XML

4.2. Book Record

Create a record for the XML model.

src/main/java/example/micronaut/Book.java
package example.micronaut;

import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement;
import io.micronaut.core.annotation.Introspected;

@Introspected (1)
@JacksonXmlRootElement(localName = "book") (2)
public record Book(@JacksonXmlProperty(isAttribute = false) String name,
                   @JacksonXmlProperty(isAttribute = true) String isbn) { (3)
}
1 Annotate the class with @Introspected to generate BeanIntrospection metadata at compilation time. This information can be used, for example, to render the POJO as JSON using Jackson without using reflection.
2 @JacksonXmlRootElement annotation defines the name of root element used for the root-level object when serialized.
3 @JacksonXmlProperty annotation provides XML-specific configuration for properties.

4.3. Book Controller

Create a controller which returns a Book instance.

src/main/java/example/micronaut/BookController.java
package example.micronaut;

import io.micronaut.http.MediaType;
import io.micronaut.http.annotation.Controller;
import io.micronaut.http.annotation.Get;
import io.micronaut.http.annotation.Produces;

@Controller("/book") (1)
class BookController {

    @Produces(MediaType.APPLICATION_XML) (2)
    @Get (3)
    Book index() {
        return new Book("Building Microservices", "1491950358");
    }
}
1 The class is defined as a controller with the @Controller annotation mapped to the path /book.
2 Set the response content-type to XML with the @Produces annotation.
3 The @Get annotation maps the method to an HTTP GET request.

5. Tests

Create a test which verifies tha the controller returns XML.

src/test/java/example/micronaut/BookControllerTest.java
package example.micronaut;

import io.micronaut.http.HttpRequest;
import io.micronaut.http.MediaType;
import io.micronaut.http.client.BlockingHttpClient;
import io.micronaut.http.client.HttpClient;
import io.micronaut.http.client.annotation.Client;
import io.micronaut.test.extensions.junit5.annotation.MicronautTest;
import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;

@MicronautTest (1)
class BookControllerTest {

    @Test
    void testXmlRendered(@Client("/") HttpClient httpClient) { (2)
        BlockingHttpClient client = httpClient.toBlocking();
        String xml = assertDoesNotThrow(() ->
                client.retrieve(HttpRequest.GET("/book").accept(MediaType.APPLICATION_XML), String.class));  (3)
        assertEquals("""
                <book isbn="1491950358"><name>Building Microservices</name></book>""", xml);
    }
}
1 Annotate the class with @MicronautTest so the Micronaut framework will initialize the application context and the embedded server. More info.
2 Inject the HttpClient bean and point it to the embedded server.
3 Creating HTTP Requests is easy thanks to the Micronaut framework fluid API.

6. Testing the Application

To run the tests:

./mvnw test

7. Native Tests

This plugin supports running tests on the JUnit Platform as native images. This means that tests will be compiled and executed as native code.

First, add the following profile to pom.xml:

 <profile>
      <id>native</id>
      <build>
        <plugins>
          <plugin>
            <groupId>org.graalvm.buildtools</groupId>
            <artifactId>native-maven-plugin</artifactId>
            <extensions>true</extensions>
            <executions>
              <execution>
                <id>test-native</id>
                <goals>
                  <goal>test</goal>
                </goals>
                <phase>test</phase>
              </execution>
            </executions>
          </plugin>
        </plugins>
      </build>
    </profile>

Then, to execute the native tests, execute:

./mvnw -Pnative test

INFO: A test may be disabled within a GraalVM native image via the @DisabledInNativeImage annotation.

8. Generate a Micronaut Application Native Executable with GraalVM

We will use GraalVM, the polyglot embeddable virtual machine, to generate a native executable of our Micronaut application.

Compiling native executables ahead of time with GraalVM improves startup time and reduces the memory footprint of JVM-based applications.

Only Java and Kotlin projects support using GraalVM’s native-image tool. Groovy relies heavily on reflection, which is only partially supported by GraalVM.

8.1. GraalVM installation

The easiest way to install GraalVM on Linux or Mac is to use SDKMan.io.

Java 17
sdk install java 17.0.12-graal
Java 17
sdk use java 17.0.12-graal

For installation on Windows, or for manual installation on Linux or Mac, see the GraalVM Getting Started documentation.

The previous command installs Oracle GraalVM, which is free to use in production and free to redistribute, at no cost, under the GraalVM Free Terms and Conditions.

Alternatively, you can use the GraalVM Community Edition:

Java 17
sdk install java 17.0.9-graalce
Java 17
sdk use java 17.0.9-graalce

8.2. Native executable generation

To generate a native executable using Maven, run:

./mvnw package -Dpackaging=native-image

The native executable is created in the target directory and can be run with target/micronautguide.

You can execute the ÷books endpoint exposed by the native executable:

curl localhost:8080/book
<book isbn="1491950358"><name>Building Microservices</name></book>

9. Next steps

Explore more features with Micronaut Guides.

Learn more about Micronaut Jackson XML.

10. Help with the Micronaut Framework

11. License

All guides are released with an Apache license 2.0 license for the code and a Creative Commons Attribution 4.0 license for the writing and media (images…​).