Building URIs - Spring Boot

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

Authors: Sergio del Amo

Micronaut Version: 5.0.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/kotlin/example/micronaut/UriComponentsBuilderTest.kt
package example.micronaut

import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Test
import org.springframework.web.util.UriComponentsBuilder

class UriComponentsBuilderTest {

    @Test
    fun youCanUseUriComponentsBuilderToBuildUris() {
        val 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/kotlin/example/micronaut/UriBuilderTest.kt
package example.micronaut

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

class UriBuilderTest {

    @Test
    fun youCanUseUriBuilderToBuildUris() {
        val 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 for the code and a Creative Commons Attribution 4.0 license for the writing and media (images).