Java / Maven

@Configuration and @ConfigurationBuilder

Learn how to use @Configuration and @ConfigurationBuilder annotations to configure declared properties.

Nirav Assar
On this guide
In this section

Getting Started

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

In this guide, you will learn how to use the annotations @ConfigurationProperties, @ConfigurationBuilder, and @EachProperty to consume configured properties in a Micronaut application. These annotations allow declared values to be injected into a bean for use in the application.

What you will need

To complete this guide, you will need the following:

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.

Writing the Application

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

mn create-app example.micronaut.micronautguide \
    --features=serialization-jackson,graalvm \
    --build=maven \
    --lang=java \
    --test=junit
Note
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 serialization-jackson, and graalvm features.

Note
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.

Team Configuration with @ConfigurationProperties

Imagine a feature where you can configure a sports team in a declarative manner. The team has a few attributes like team name, color, and players.

src/main/resources/application.properties
team.name=Steelers
team.color=Black
team.player-names[0]=Mason Rudolph
team.player-names[1]=James Connor

With Micronaut Framework, you can use the @ConfigurationProperties annotation to bind the configuration into a bean. Each property that matches the configuration in application.properties will call the setter in the bean. The bean will then be available for injection in the application.

java/src/main/java/example/micronaut/TeamConfiguration.java
@ConfigurationProperties("team")
public class TeamConfiguration {
    private String name;
    private String color;
    private List<String> playerNames;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getColor() {
        return color;
    }

    public void setColor(String color) {
        this.color = color;
    }

    public List<String> getPlayerNames() {
        return playerNames;
    }

    public void setPlayerNames(List<String> playerNames) {
        this.playerNames = playerNames;
    }
}

Test @ConfigurationProperties

Let’s validate that the bean is available in the application context and is created with the values declared in the application.properties.

java/src/test/java/example/micronaut/TeamConfigurationTest.java

Team Admin Builder with @ConfigurationBuilder

The Builder pattern is a great way to build configuration objects incrementally. Read about the Builder pattern in this DZone article to learn more. Micronaut Framework supports the Builder pattern with @ConfigurationBuilder.

Suppose you want to add team administrators to a team. The team administration is composed by using a builder pattern object. You can add a coach, manager, and president to the team.

src/main/resources/application.properties

The TeamAdmin object abides by the Builder pattern.

java/src/main/java/example/micronaut/TeamAdmin.java

At the bottom of TeamConfiguration, add the inner class TeamAdmin.Builder and annotate it with @ConfigurationBuilder. This tells Micronaut Framework that configuration can be read and an object can be constructed using the Builder pattern.

Note
The builder is used only here, so call builder.build() later to get the TeamAdmin object. In this guide, the JUnit test calls builder.build().
java/src/main/java/example/micronaut/TeamConfiguration.java

Test @ConfigurationBuilder

Validate that @ConfigurationBuilder is applied properly with the following JUnit test. The test format is similar to previous tests.

java/src/test/java/example/micronaut/TeamConfigurationTest.java

Stadiums with @EachProperty

Micronaut Framework is also able to read a list of related configurations. Imagine you would like to declare stadiums and their attributes.

src/main/resources/application.properties

You can use @EachProperty to cycle through the configuration and read each nested clause as a bean. The higher-level property will be parameterized as the name.

java/src/main/java/example/micronaut/StadiumConfiguration.java

Test @EachProperty

Validate the configuration with a test. Notice multiple beans are created from the configuration. In a controller, you can inject a particular StadiumConfiguration instance bean by using the @Named parameter with a qualifier name.

java/src/test/java/example/micronaut/StadiumConfigurationTest.java

Running the Application

To run the application, use the ./mvnw mn:run command, which starts the application on port 8080.

Controller

Configuration beans can be injected into the application just like any other beans. As a demonstration, create a controller where the beans are constructor injected. The StadiumConfiguration class has two instances, so for injection you need to use the @Named annotation with a qualifier name to specify the bean.

java/src/main/java/example/micronaut/MyController.java

Add test:

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

import io.micronaut.http.HttpRequest;
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 jakarta.inject.Inject;

import java.util.Arrays;
import java.util.List;

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

@MicronautTest
public class MyControllerTest {

    @Inject
    @Client("/")
    HttpClient client;

    @Test
    void testMyTeam() {
        TeamConfiguration teamConfiguration = client.toBlocking()
                .retrieve(HttpRequest.GET("/my/team"), TeamConfiguration.class);
        assertEquals("Steelers", teamConfiguration.getName());
        assertEquals("Black", teamConfiguration.getColor());
        List<String> expectedPlayers = Arrays.asList("Mason Rudolph", "James Connor");
        assertEquals(expectedPlayers.size(), teamConfiguration.getPlayerNames().size());
        expectedPlayers.forEach(name -> assertTrue(teamConfiguration.getPlayerNames().contains(name)));
    }

    @Test
    void testMyStadium() {
        StadiumConfiguration conf = client.toBlocking()
                .retrieve(HttpRequest.GET("/my/stadium"), StadiumConfiguration.class);
        assertEquals("Pittsburgh", conf.getCity());
        assertEquals(35000, conf.getSize());
    }
}

Generate a Micronaut Application Native Executable with GraalVM

We will use GraalVM, an advanced JDK with ahead-of-time Native Image compilation, to generate a native executable of this Micronaut application.

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

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

GraalVM Installation

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

Java 25
sdk install java 25.0.2-graal

For installation on Windows, or for a 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 25
sdk install java 25.0.2-graalce

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.

It is possible to customize the name of the native executable or pass additional build arguments using the Maven plugin for GraalVM Native Image building. Declare the plugin as follows:

pom.xml

You can invoke the controller exposed by the native executable:

curl http://localhost:8080/my/stadium
curl http://localhost:8080/my/team

Next Steps

Help with the Micronaut Framework

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

License

Note
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).