Skip to content
javahacks.dev
Micronaut

Micronaut Tutorial for Beginners With a REST Controller

Create a Micronaut 4 application, add a REST controller and a service, run it and test it, and see how compile-time injection differs from Spring.

6 min read
Summarize in AI
Flat illustration of a browser and a server trading a request and a response, with the Spring, NGINX, Spring Boot and GraphQL logos.

Micronaut is a JVM framework that moves dependency injection and configuration processing to compile time, aiming for fast startup and low memory use. In daily work it feels like a lean Spring Boot: controllers, services, constructor injection and a test annotation that starts the application. The difference is what happens before the program runs. This tutorial builds a small REST service on Micronaut 4 with Java, from the generator to a passing test, and points out where the compile-time model changes what you write. The reasoning behind the speed is in what Micronaut is.

Generate the project

Go to launch.micronaut.io, choose Application, Java, Maven or Gradle, the latest Micronaut 4 version, and the serialization-jackson feature, then download the zip. The command-line tool does the same:

Shell
mn create-app dev.javahacks.hello --build=maven --lang=java

Open the generated project and look at four files.

FilePurpose
pom.xmlDependencies and the annotation processors
Application.javaThe entry point, a call to Micronaut.run
src/main/resources/application.properties or .ymlConfiguration
src/test/java/...A sample test

The annotation processors in the build file matter more than they look. They run during compilation and generate the injection code. If a project builds but beans are missing at runtime, the processor is often not configured, which is the first thing to check.

A service and a controller

java
package dev.javahacks.hello;

import jakarta.inject.Singleton;

@Singleton
public class GreetingService {

    public String greet(String name) {
        return "Hello, " + name + "!";
    }
}
java
package dev.javahacks.hello;

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

@Controller("/hello")
public class HelloController {

    private final GreetingService greetings;

    public HelloController(GreetingService greetings) {
        this.greetings = greetings;
    }

    @Get("/{name}")
    public String hello(String name) {
        return greetings.greet(name);
    }
}

@Singleton comes from jakarta.inject and marks a bean, one instance for the application. @Controller exposes the class's methods as HTTP endpoints under the given path. The path variable {name} binds to the method parameter of the same name, so no @PathVariable is needed. The constructor injects the service with no annotation at all. When the processor compiles HelloController, it generates the code that calls this constructor with the singleton, so at runtime there is no scanning and no reflection to find it.

That has a practical consequence. Add a new bean, and the build must run the processor again before the bean exists. In an IDE, if injection fails after a change, rebuild the project before suspecting your code.

Run it

Shell
./mvnw mn:run

The log prints Startup completed in followed by a time, usually a few hundred milliseconds for a small service, and the address http://localhost:8080. Request http://localhost:8080/hello/ana and the response is Hello, ana!. Change the port in application.properties with micronaut.server.port=9090 when 8080 is taken.

Return an object or a record and Micronaut writes it as JSON:

java
@Serdeable
public record Greeting(String message) {
}

@Get("/json/{name}")
public Greeting json(String name) {
    return new Greeting(greetings.greet(name));
}

The @Serdeable annotation matters. Micronaut Serde generates serializers at compile time, and it processes only the types you mark. A record without it compiles, runs, and fails at the first request with an error that says no serializer exists for the type. That message is the clue, and the fix is the annotation.

Test it

java
package dev.javahacks.hello;

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

import io.micronaut.http.client.HttpClient;
import io.micronaut.http.client.annotation.Client;
import io.micronaut.test.extensions.junit5.annotation.MicronautTest;
import jakarta.inject.Inject;
import org.junit.jupiter.api.Test;

@MicronautTest
class HelloControllerTest {

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

    @Test
    void greetsByName() {
        String body = client.toBlocking().retrieve("/hello/ana");
        assertEquals("Hello, ana!", body);
    }
}

@MicronautTest starts the application on a random port and injects a client that points at it, so the test uses the real HTTP stack without a fixed port. toBlocking() turns the reactive client into a plain call, which suits a test. Add a second test for an error path, such as a request to a path that does not exist, and assert the status with HttpClientResponseException. The testing options, including mocking a bean with @MockBean, are in testing Micronaut apps.

How it differs from Spring in daily use

Four differences show up in the first week. Beans are resolved at compile time, so a missing bean is often a build-time failure, with a clearer message than a runtime exception. There is no classpath scanning at startup, which is where the fast start comes from. Reflection is avoided, so the framework works well with native image builds. And configuration is checked: a typed @ConfigurationProperties class fails at startup when a value is wrong. The trade is that the build does more work, and that libraries written for runtime reflection need Micronaut-specific support.

Configuration and profiles

Settings live in application.properties or application.yml, and an environment variable overrides a file value, with the usual translation: MICRONAUT_SERVER_PORT becomes micronaut.server.port. Bind a group of settings to a class with @ConfigurationProperties("greeting"), and Micronaut checks the values at startup, so a missing required property stops the application with a message that names it. Environments are selected with MICRONAUT_ENVIRONMENTS=dev, and a file named application-dev.properties is loaded in addition to the base one.

Because the work happens at compile time, a typo in a property name inside a typed class is a build error rather than a runtime surprise, which is a real advantage when you are learning.

Health and metrics

Add the management feature when you generate the project and the application exposes /health and other endpoints, with the same purpose as Spring Boot's Actuator. A load balancer or Kubernetes probe calls /health, and the endpoint reports the state of the database, disk and any custom indicator you write. Turn on only what you need, and protect the sensitive endpoints, since information about the runtime is useful to an attacker.

Common first mistakes

Three mistakes account for most beginner questions. A bean is not found because the annotation processor did not run, which a clean rebuild fixes. A JSON response fails because the type is missing @Serdeable. And a controller returns 404 because the route in @Get does not match the call, so print the routes in the startup log to compare. Reading the first error line, and not the last, is the habit that saves time with all three.

Accept a body, validate it and test with the HTTP client

A first endpoint that only returns text does not show how Micronaut handles input. Add a record for the request, mark it serializable at compile time and validate it:

java
@Serdeable
public record CreateGreeting(@NotBlank String name, @Size(max = 20) String language) {}

@Controller("/greetings")
@Validated
class GreetingController {

    private final GreetingService service;

    GreetingController(GreetingService service) {
        this.service = service;
    }

    @Post
    @Status(HttpStatus.CREATED)
    String create(@Valid @Body CreateGreeting request) {
        return service.greet(request.name(), request.language());
    }
}

@Serdeable generates the serializer when the project compiles, so no reflection is needed at startup, which is the point of Micronaut's design. A request with a blank name returns 400 before the method runs. The test uses the injected HTTP client against a real embedded server:

java
@MicronautTest
class GreetingControllerTest {

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

    @Test
    void createsAGreeting() {
        String body = client.toBlocking().retrieve(
            HttpRequest.POST("/greetings", new CreateGreeting("Ada", "en")), String.class);
        assertEquals("Hello, Ada", body);
    }

    @Test
    void rejectsABlankName() {
        var error = assertThrows(HttpClientResponseException.class, () ->
            client.toBlocking().exchange(HttpRequest.POST("/greetings", new CreateGreeting(" ", "en"))));
        assertEquals(HttpStatus.BAD_REQUEST, error.getStatus());
    }
}

The client throws for any non-success status, which is why the second test expects an exception. That is a Micronaut convention that surprises Spring developers, so read the status from the exception.

Next steps

Add a database with Micronaut Data, secure the endpoints with JWT, or build a native image. When a bean goes missing, the no-bean error lists the causes in the order they usually occur. The Micronaut guide is the full reference, and guides.micronaut.io has task-focused tutorials for the next step.

Also inSpring MVC
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.