Skip to content
javahacks.dev
Micronaut

What Micronaut Is and How Compile Time DI Works in Practice

Micronaut generates its dependency injection code during compilation instead of scanning at startup. See what that gives you and what it costs.

5 min read
Summarize in AI
Flat illustration of startup time of a JVM compared with a native image, with the Spring, Spring Boot and Kubernetes logos.

Spring discovers beans when the application starts: it scans, reads annotations by reflection and builds proxies. Micronaut does that work when you compile. The result is an application that starts faster and holds less metadata in memory, at the price of a stricter model. Understanding the difference makes the framework predictable. The same idea drives why Quarkus starts fast, and the Spring approach is in how the Spring container works.

What the processor generates

For every class that is a bean, the processor writes a companion class:

Text
GreetingService.java        (your source)
$GreetingService$Definition.class   (generated bean definition: how to create it, what it needs)
$GreetingService$Definition$Reference.class

The definition contains plain Java code that calls constructors and sets fields directly. There is no Constructor.newInstance and no field reflection. Likewise for @Controller methods: the router metadata is generated, so Micronaut knows each route and its parameter types without inspecting your class at startup.

The runtime

At startup the context loads the generated definitions, orders them by dependency and creates singletons. Nothing is discovered. The consequences:

PropertyResult
No scanningStartup time does not grow with classpath size
No reflection for wiringSmaller metadata and no --reflection configuration for DI in native images
No runtime proxies for AOPAspects such as @Transactional generate subclasses at compile time
Conditions evaluated on metadata@Requires decides without loading the class

Compile-time AOP

Micronaut implements aspects (caching, transactions, validation, retry) by generating a subclass or an interceptor chain at compile time. That avoids runtime bytecode generation. A consequence you will notice: an advised class cannot be final, and a method with an annotation like @Cacheable must be public or package-private depending on the aspect. The self-invocation limitation remains; a call inside the same class is not intercepted, as in [Spring's @Transactional trap](/library/transactional-not-working-fix-self-called).

What it costs

The annotation processor has to run, and everything works only if it does. A project without it fails with no bean of type exists. Some mistakes become compile errors, such as an injection point that cannot be satisfied in certain cases, which is helpful. Dynamic features that Spring users take for granted, such as scanning arbitrary packages at runtime or registering bean definitions from a database, are restricted. Reflection-based libraries need explicit configuration for native images.

Comparison with Spring and Quarkus

Spring BootMicronautQuarkus
Bean discoveryRuntime scan (AOT optional)Compile-time processorBuild-time augmentation
Injection modelSpring annotationsJSR-330 (jakarta.inject)CDI Lite
Native imageSupportedFirst-classFirst-class
Ecosystem sizeVery largeMediumMedium

The ecosystem row is the one that decides most real choices. Spring has a library for everything. Micronaut and Quarkus have fewer, with focused modules for the common needs.

Look at what the processor generated

The claim that Micronaut works at compile time can be checked by opening the build output. After a build, the generated classes sit next to the compiled ones:

Shell
./mvnw -q compile
find target/classes -name '$*Definition*.class' | head

For a class OrderService, expect files named like $OrderService$Definition.class and $OrderService$Definition$Reference.class. The first holds the code that creates the bean and injects its dependencies, written as ordinary method calls, and the second describes the bean to the container. A bean with no such file was not processed, and no annotation will make it appear at runtime. That is the cause of most "bean not found" errors in a new project: the annotation processor is not configured, so nothing was generated.

Check the processors are configured

In Maven, the processors are listed in the compiler plugin, and the parent POM normally does this for you. A project that overrides annotationProcessorPaths replaces the list, and must repeat the Micronaut entries:

XML
<annotationProcessorPaths>
    <path>
        <groupId>io.micronaut</groupId>
        <artifactId>micronaut-inject-java</artifactId>
        <version>${micronaut.core.version}</version>
    </path>
</annotationProcessorPaths>

In Gradle the equivalent is annotationProcessor("io.micronaut:micronaut-inject-java"). A processor on the regular classpath does nothing in modern JDKs, since they require it on the processor path. When a Lombok or MapStruct processor is added later, the order matters too, and Lombok must run before the Micronaut processor so that generated getters are visible.

Nothing is found by reflection, so tell the framework

The compile-time model means a class that the framework must see at runtime needs a marker. Serialisation of a type that has no other annotation is the usual case:

java
@Serdeable
public record OrderView(long id, String status) { }

@Serdeable generates the serialiser at compile time. Without it, a controller that returns the record fails at runtime with an error about no serialiser being found. The @Introspected annotation does the same for bean introspection used by validation and data binding. These annotations are the price of avoiding reflection, and they are added once per type.

Tests start a real context quickly

Because the work is done at compile time, a context starts in a fraction of the time a scanning container needs. A test can build one per method:

java
@Test
void resolvesServiceWithoutServer() {
    try (ApplicationContext ctx = ApplicationContext.run()) {
        OrderService service = ctx.getBean(OrderService.class);
        assertNotNull(service);
    }
}

The test runs in tens of milliseconds for a small application, so it can run on every build without a slice mechanism. A context that fails to start names the bean and the missing dependency in the message, and the problem is the same one the compiler could have reported.

Compile time is the cost

Every change to an annotated class regenerates its definition, and a large project spends more time in compilation. Incremental builds help, and a change to a widely used interface triggers a larger rebuild. Keep modules small, and measure a clean build before and after adding the framework. A project of a few hundred beans compiles in seconds, and one with thousands of introspected types may add a noticeable amount.

QuestionCompile-time DI answer
When is a missing bean found?At startup, with a clear message, or at build time for some checks
Can a bean be registered at runtime from a string?Only through explicit APIs, not by scanning
How do you debug wiring?Read the generated definition, set a breakpoint in it
What if a library uses reflection?Add reflection configuration, or an introspection annotation

When Micronaut is the wrong tool

If your team knows Spring and your libraries are Spring-first, the startup benefit rarely justifies a move. Micronaut suits serverless functions, command-line tools and microservices where startup and memory matter, and teams that like compile-time safety. The Micronaut guide and the Micronaut internals chapter describe the model, and the tutorial shows it running.

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.