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: 4.3.8

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.

7. 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…​).