Skip to content
Tutorials Center
My learning

Topics

Lesson 5 of 38 ยท Getting Started

Ahead-of-Time Compilation

How Micronaut's annotation processors generate bean definitions, introspection and AOP advice during the build, so no reflection or runtime proxies are needed.

Everything fast about Micronaut traces back to one design decision: do the framework's thinking during the build. This lesson looks inside that step. You will see what the annotation processor reads, what classes it writes, why that removes reflection and runtime proxies, and what the practical consequences are for how you write code.

Micronaut itself is not installed on this site, so the real code and generated class names are shown read-only. The two runnable programs are Java stand-ins: a miniature "processor" that turns a class model into generated source text and checks the graph, and a hand-written version of the subclass that compile-time AOP generates.

The compile-time pipeline

When javac compiles your project, it also runs every annotation processor on the classpath. Micronaut's processor (micronaut-inject-java, or the KSP/Kapt equivalent for Kotlin) looks at classes carrying DI annotations, then writes extra .class files next to yours.

flowchart LR
    A["@Singleton class OrderService"] --> P["Annotation processor"]
    B["@Controller class OrderController"] --> P
    P --> D1["$OrderService$Definition"]
    P --> D2["$OrderController$Definition"]
    P --> M["META-INF service index"]
    D1 --> R["Runtime container"]
    D2 --> R
    M --> R

The processor writes one definition per bean and an index the container can read without scanning.

For a class like this:

Java
@Singleton
class OrderService {
    private final OrderRepository repo;
    OrderService(OrderRepository repo) { this.repo = repo; }
}

the processor generates a class whose name starts with a dollar sign, such as $OrderService$Definition. It records the constructor, its parameter types, the scope, qualifiers, and any annotations that matter. At runtime the container calls the generated instantiate method, which executes a normal new OrderService(repo) expression. No Constructor.newInstance, no setAccessible, no name lookups.

Three things that get generated

Generated artifact Replaces runtime... Used for
Bean definition Classpath scanning and constructor reflection Creating and injecting beans
Introspection (@Introspected, @Serdeable) getDeclaredFields, Method.invoke Reading and writing properties, JSON serialization, validation
AOP advice classes CGLIB or JDK dynamic proxies @Transactional, @Cacheable, @Retryable, validation, your own interceptors

Introspection

Libraries often need to read an object's properties: a JSON encoder, a validator, a data mapper. Normally that means reflection. With @Introspected, the processor produces a class that exposes the property list and getters and setters as direct calls:

Java
@Introspected
public record Book(String title, int pages) {}

JSON serialization in Micronaut Serialization uses the same trick through @Serdeable, which is why you must annotate types you send over the wire (see JSON and Serialization).

Compile-time AOP

Spring's @Transactional works by creating a proxy object at runtime. Micronaut's advice annotations are handled by generating a subclass at compile time. Your class must therefore not be final, and the advised methods must not be private or final (the processor tells you if they are). The generated subclass overrides each advised method and routes the call through a chain of interceptors.

Practical consequences

  • Errors arrive at build time. An injection point with no matching bean fails compilation. In practice this catches typos and missing qualifiers early.
  • Reflection-free means native-friendly. GraalVM's closed-world analysis can see all the code, so images are small and need little hand-written configuration.
  • Generated sources are visible. Look under build/generated/sources/annotationProcessor. Reading one is the quickest way to understand any behavior you do not expect.
  • Processors must be on the right path. In Gradle that is annotationProcessor("io.micronaut:micronaut-inject-java"); the generated project already has it. If you add a library that has its own processor (validation, serialization, data), add it to annotationProcessor as well, not just implementation.
  • Kotlin uses KSP. Use the ksp(...) configuration instead of annotationProcessor.
  • Dynamic tricks are limited. Code that discovers classes by name at runtime, or that relies on private fields being injected, will not work the way it would in a reflection-based framework.

Reflection vs generated code

Reflection Inspect classes while the app runs.
Generated code Plain Java written during the build.

Plain Java is faster and visible to GraalVM.

1 / 2

Stand-in 1: a miniature annotation processor

A real processor reads the compiler's model of your code. This stand-in reads a small description of classes and does what Micronaut does with them: generates source text for each definition and validates that every constructor parameter has a provider. It is educational only, and the generated text is a simplified shape of what a framework would write.

Java Generate definitions and validate the graph

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Stand-in 2: the subclass AOP generates

For a method annotated with an advice annotation, Micronaut writes a subclass roughly like the one below. This is hand-written to show the shape: the original class stays untouched, and the subclass wraps each call in an interceptor chain. Compare it with a runtime proxy: here the type is known when the program is compiled, so there is nothing to generate while it runs.

Java Interceptors through a generated subclass

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Because the proxy is a real subclass, final classes cannot be advised. Micronaut reports that error during the build. Keep this in mind in Kotlin too, where classes are final by default: the kotlin-allopen plugin, configured by the generated project, opens classes that carry Micronaut annotations.

What to do with this knowledge

When something surprises you, check the generated sources first. When you add a library that uses annotations, check whether it needs an annotation processor. When you write advice, keep advised classes open and avoid private methods. Beans and their scopes come next in Beans and Singletons.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does the Micronaut annotation processor generate for a @Singleton class?

    A definition class records the constructor, scope and dependencies and instantiates the bean without reflection.
  2. 2. How does Micronaut implement advice such as @Retryable?

    Compile-time AOP generates a subclass, so advised classes and methods must not be final or private.
  3. 3. A library you added uses annotations but nothing happens. What should you check?

    Processors run only if they are on the processor path, not just the normal compile classpath.
  4. 4. Where can you inspect the generated classes in a Gradle build?

    Generated sources are written below build/generated; reading them explains many behaviors.

Summary

  • The annotation processor generates bean definitions, introspections and AOP subclasses during compilation.
  • No reflection or runtime proxies are required, which helps startup, memory and native images.
  • Unsatisfied injection points and illegal advice targets fail the build.
  • Libraries with annotations may need their own processor on the annotationProcessor (or ksp) path.
  • Look in build/generated/sources/annotationProcessor to see what was written.

Next: Beans and Singletons