Skip to content
Tutorials Center
My learning

Topics

Lesson 10 of 38 ยท Beans and Dependency Injection

AOP and Method Interceptors

Add logging, caching, retries and timing to Micronaut beans without touching their code, using @Around advice and MethodInterceptor. Includes runnable stand-ins.

Some code does not belong inside your business methods: timing how long a call took, retrying a flaky call, checking a permission, opening a transaction. This kind of cross-cutting work is the reason for aspect-oriented programming (AOP). You write the extra behavior once, attach it to methods with an annotation, and the framework runs it around the method for you.

Micronaut does AOP without runtime proxies built by reflection. At compile time it generates a subclass of your bean that overrides the annotated methods and calls an interceptor chain. This lesson shows the real API as read-only code, then two runnable Java stand-ins that use java.lang.reflect.Proxy to demonstrate the same shape: a method call goes into an interceptor, the interceptor decides whether and how to call the real method, and then returns a result.

The pieces

Three parts work together:

  1. An annotation that marks where the behavior applies, such as @Retryable or your own @Timed.
  2. An interceptor, a bean that implements MethodInterceptor<T, R>.
  3. A binding that connects them, written as @Around on the annotation plus @InterceptorBean on the interceptor.
Java
import io.micronaut.aop.Around;
import io.micronaut.context.annotation.Type;
import java.lang.annotation.*;

@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.TYPE})
@Around
@Type(TimedInterceptor.class)
public @interface Timed {
}

@Around tells Micronaut that methods carrying this annotation are wrapped by advice. @Type names the interceptor bean that does the wrapping. Using the annotation then looks like this:

Java
@Singleton
public class ReportService {

    @Timed
    public String buildReport(String name) {
        // slow work
        return "report:" + name;
    }
}

Because the interceptor is generated into a subclass at build time, the bean class must not be final and annotated methods must not be final or private. Micronaut reports a compile error if you break these rules, which is better than a mysterious failure at runtime.

Writing an interceptor

An interceptor receives a MethodInvocationContext, which describes the call: the target object, the method name, the parameter values and the annotations. Calling context.proceed() runs the next interceptor in the chain or, at the end, the real method.

Java
import io.micronaut.aop.InterceptorBean;
import io.micronaut.aop.MethodInterceptor;
import io.micronaut.aop.MethodInvocationContext;
import jakarta.inject.Singleton;

@Singleton
@InterceptorBean(Timed.class)
public class TimedInterceptor implements MethodInterceptor<Object, Object> {

    @Override
    public Object intercept(MethodInvocationContext<Object, Object> context) {
        long start = System.nanoTime();
        try {
            return context.proceed();
        } finally {
            long micros = (System.nanoTime() - start) / 1_000;
            System.out.println(context.getMethodName() + " took " + micros + " us");
        }
    }
}

Notice the three powers an interceptor has:

  • Before and after. Code before proceed() runs before the method; code after it runs after.
  • Replace the result. Return something else and the caller never sees the original value. A cache does exactly this.
  • Skip the call. Not calling proceed() at all means the real method never runs, which is how a security check refuses a call.

If several annotations apply to one method, their interceptors form a chain ordered by their @Order values or by the Ordered interface.

Built-in advice you will use

Micronaut ships many annotations that are implemented as interceptors, so you rarely need to write one:

Annotation Purpose
@Retryable Re-run a failing method with delay and attempt limits
@CircuitBreaker Stop calling a method that keeps failing, then probe again
@Fallback Provide a replacement bean when the real one fails
@Cacheable, @CacheInvalidate Cache results by method arguments
@Transactional Open and commit a database transaction
@Scheduled Run a method on a timer
@Async Run a method on another thread pool
Constraint annotations Validate arguments before the call
Java
@Singleton
public class PriceClient {

    @Retryable(attempts = "3", delay = "200ms", multiplier = "2.0")
    public double fetchPrice(String sku) {
        return remote.get(sku);   // may throw; retried up to 3 times
    }
}

Where the advice runs

Caller Calls the method as usual.
Interceptor chain Each interceptor wraps the next.
Real method Runs at the end of the chain.

The caller never knows advice is attached.

1 / 2

Stand-in 1: an interceptor chain with a dynamic proxy

Micronaut itself is not available on this site. The program below uses java.lang.reflect.Proxy, which builds a stand-in object at runtime. It has the same shape as Micronaut's generated subclass: every call goes to an invoke method that runs interceptors around the target. Interceptors are listed in order; each one receives a proceed function.

Java A hand-made interceptor chain

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.

The logging interceptor runs outermost, so it sees the result after the shouting interceptor changed it. Change the order in List.of(...) and the log shows the original text instead. That ordering effect is real in Micronaut too, and it explains many "why is my cache storing the wrong value" questions.

Stand-in 2: retry and fallback

@Retryable is the most common built-in advice. The stand-in below shows its logic in a plain method: try, wait, try again, and give up with a fallback after the attempt limit. To keep the output the same every time, the flaky service is deterministic: it fails on its first calls and then succeeds. The "delay" is printed rather than slept.

Java Retry with backoff, then fallback

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.

In Micronaut the same behavior is three annotation attributes. The delays grow by the multiplier, so retries do not hammer a struggling service. Pair @Retryable with @Fallback or @CircuitBreaker when failures can last a long time.

Practical advice

  • Keep interceptors small and fast. They run on every call of every annotated method.
  • Avoid self-calls. Calling an annotated method from another method of the same bean goes through this, which can bypass the generated subclass in some setups. Test it, or move the annotated method to another bean.
  • Do not annotate everything. Prefer annotating the service boundary rather than each small helper.
  • Mind the order. @Transactional outside @Retryable retries inside one transaction; the reverse retries the whole transaction. Decide which you want.
  • Prefer built-ins. Writing your own is for genuinely application-specific rules, such as an audit trail.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. When does Micronaut create the code that wraps an annotated method?

    Micronaut's annotation processors generate the wrapping classes during compilation, which keeps start-up fast.
  2. 2. What does context.proceed() do inside an interceptor?

    proceed() hands control to the rest of the chain. An interceptor that never calls it prevents the method from running.
  3. 3. Which is NOT allowed on a method that has AOP advice attached?

    Generated subclasses override the method, so a final method cannot be advised and the build fails.
  4. 4. You put @Retryable and @Cacheable on one method. Why does the order of interceptors matter?

    Chains are nested. Whichever interceptor is outermost sees the final result of everything inside it.

Summary

  • AOP lets you attach cross-cutting behavior to methods with annotations.
  • @Around plus @Type (or @InterceptorBean) connects an annotation to a MethodInterceptor.
  • Interceptors can run code before and after, change the result or skip the call.
  • Micronaut generates the wrapper subclass at compile time, so annotated classes and methods cannot be final.
  • Built-in advice such as @Retryable, @Cacheable, @Transactional and @Scheduled covers most needs.
  • Interceptor order changes behavior; decide it deliberately.

Next: Controllers and Routing