These tutorials target Micronaut Framework 3. Read, Guides for Micronaut Framework 4.

Building URIs - Spring Boot to Micronaut Framework

This guide compares using Spring’s UriComponentsBuilder vs Micronaut Framework’s UriBuilder.

Authors: Sergio del Amo

Micronaut Version: 3.9.2

1. Sample Project

You can download a sample application with the code examples in this article.

2. Introduction

While developing web applications, we often need to build URIs. For example, to create redirection responses. In this article, we compare two similar APIs - Spring UriComponentsBuilder and Micronaut UriBuilder.

3. Spring Boot UriComponentsBuilder

springboot/src/test/java/example/micronaut/UriComponentsBuilderTest.java
package example.micronaut;

import org.junit.jupiter.api.Test;
import org.springframework.web.util.UriComponentsBuilder;

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

public class UriComponentsBuilderTest {

    @Test
    void youCanUseUriComponentsBuilderToBuildUris() {
        String isbn = "1680502395";
        assertEquals("/book/1680502395?lang=es", UriComponentsBuilder.fromUriString("/book")
                .path("/" + isbn)
                .queryParam("lang", "es")
                .build()
                .toUriString());
    }
}

4. Micronaut UriBuilder

As you can see in the following code snippet, the API is similar. You should be able to migrate easily.

micronautframework/src/test/java/example/micronaut/UriBuilderTest.java
package example.micronaut;

import io.micronaut.http.uri.UriBuilder;
import org.junit.jupiter.api.Test;

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

public class UriBuilderTest {

    @Test
    void youCanUseUriBuilderToBuildUris() {
        String isbn = "1680502395";
        assertEquals("/book/1680502395?lang=es", UriBuilder.of("/book")
                .path(isbn)
                .queryParam("lang", "es")
                .build()
                .toString());
    }
}

5. Next steps

Read more about Micronaut Spring.

6. Help with the Micronaut Framework

The Micronaut Foundation sponsored the creation of this Guide. A variety of consulting and support services are available.