Skip to content
Tutorials Center
My learning

Topics

Lesson 9 of 36 ยท Dependency Injection and CDI

Interceptors and Decorators

Add logging, timing, security and retries to Quarkus beans without touching their code: interceptor bindings, @AroundInvoke, priorities, decorators and stereotypes.

Some logic belongs to many methods and to none of them in particular: logging every call, measuring duration, checking permissions, retrying on failure, opening a transaction. Copying that code into every method clutters the business logic. CDI offers interceptors for exactly this. An interceptor wraps a method call, so it can run code before, after or around it. You mark methods or classes with an annotation, and the container does the rest.

You already meet interceptors when you use @Transactional, @Retry, @Timeout or @RolesAllowed. In this lesson you will write your own, control their order and learn about decorators, which wrap a specific interface rather than an annotation. The real CDI code is read-only; the runnable examples use java.lang.reflect.Proxy to rebuild the interceptor chain in plain Java.

An interceptor binding

You need two pieces: an annotation (the binding) that you place on beans, and an interceptor class that does the work.

Java
import jakarta.interceptor.InterceptorBinding;
import java.lang.annotation.*;

@InterceptorBinding
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.METHOD})
public @interface Logged {
}
Java
import jakarta.annotation.Priority;
import jakarta.interceptor.AroundInvoke;
import jakarta.interceptor.Interceptor;
import jakarta.interceptor.InvocationContext;
import org.jboss.logging.Logger;

@Logged
@Interceptor
@Priority(Interceptor.Priority.APPLICATION)
public class LoggingInterceptor {

    private static final Logger LOG = Logger.getLogger(LoggingInterceptor.class);

    @AroundInvoke
    Object log(InvocationContext context) throws Exception {
        String name = context.getMethod().getName();
        LOG.infof("-> %s", name);
        try {
            return context.proceed();           // call the real method
        } finally {
            LOG.infof("<- %s", name);
        }
    }
}

Now apply the binding:

Java
@ApplicationScoped
public class PaymentService {

    @Logged
    public void charge(String account, long cents) {
        // only business logic here
    }
}

Every call to charge now goes through LoggingInterceptor.log. The key piece is context.proceed(): it calls the next interceptor or, at the end of the chain, the real method. You may skip it (to block the call), change arguments with context.setParameters(...), replace the result or handle exceptions.

One call, three layers

Logging Records the call before and after.
Timing Measures how long it took.
Target Your plain business method.

Each interceptor calls proceed() to go one layer deeper.

1 / 2

Ordering with priorities

@Priority on an interceptor enables it (in Quarkus, interceptors need one) and orders it. Lower numbers run first, meaning they wrap the outside. Jakarta defines constants:

Constant Value Typical use
Interceptor.Priority.PLATFORM_BEFORE 0 Very early platform interceptors
Interceptor.Priority.LIBRARY_BEFORE 1000 Library interceptors
Interceptor.Priority.APPLICATION 2000 Your application interceptors
Interceptor.Priority.LIBRARY_AFTER 3000 Late library interceptors

With a logging interceptor at 2000 and a timing interceptor at 2100, logging wraps timing, so the log includes the timing interceptor's overhead and the order of "before" lines is log, then timing.

Seeing the chain

The stand-in below builds an interceptor chain around a service using a dynamic proxy. Interceptors are sorted by priority, each receives a proceed callback and the printed trace shows the nesting: the lowest priority number is the outermost layer.

Java Stand-in: an interceptor chain with priorities

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.

Notice that the list gave timing() first, yet logging is outermost because its priority number (2000) is lower. In Quarkus you write the same thing as two @Priority values.

Interceptor binding with members

Bindings can carry parameters. Mark members with @Nonbinding if the interceptor should be applied regardless of their value, and read them inside the interceptor:

Java
@InterceptorBinding
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.METHOD})
public @interface Audited {
    @Nonbinding String action() default "";
}
Java
@Audited
@Interceptor
@Priority(Interceptor.Priority.APPLICATION + 10)
public class AuditInterceptor {

    @AroundInvoke
    Object audit(InvocationContext ctx) throws Exception {
        Audited a = ctx.getMethod().getAnnotation(Audited.class);
        // a.action() available here
        return ctx.proceed();
    }
}

Stereotypes: bundling annotations

If you keep repeating the same combination, such as a scope plus an interceptor binding, create a stereotype:

Java
import jakarta.enterprise.inject.Stereotype;

@Stereotype
@ApplicationScoped
@Logged
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface LoggedService {
}

@LoggedService
public class ReportService { /* an application-scoped bean whose calls are logged */ }

Decorators

An interceptor works for any bean carrying a binding and knows nothing about business meaning. A decorator is tied to a Java interface. It implements that interface, receives the real bean as a delegate and can alter specific methods with business knowledge:

Java
import jakarta.annotation.Priority;
import jakarta.decorator.Decorator;
import jakarta.decorator.Delegate;
import jakarta.inject.Inject;

@Decorator
@Priority(100)
public abstract class RoundingDecorator implements PaymentService {

    @Inject
    @Delegate
    PaymentService delegate;

    @Override
    public String charge(String account, long cents) {
        long rounded = (cents / 5) * 5;          // business rule: round down to 5 cents
        return delegate.charge(account, rounded);
    }
}

The decorator is abstract, so it only implements the methods it wants to change; calls to other methods pass straight to the delegate. A decorator can only decorate bean types, so it works on interface calls and is a good fit for rules such as rounding, currency conversion or caching on a specific interface.

When to use which

Need Use
The same extra behaviour on many unrelated beans Interceptor
Behaviour specific to one interface Decorator
React to something that happened Events (next lesson)
Extra logic on REST requests/responses only A REST filter (REST Client and Filters)

A decorator stand-in

This second stand-in builds a decorator with plain Java. The decorator implements the same interface, holds the delegate and changes one method while forwarding the others.

Java Stand-in: a decorator around a delegate

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.

Interceptors only run for calls that arrive through the container (through a proxy or the bean's subclass). A method calling another method of the same object (this.helper()) is a self-invocation. Quarkus ArC handles self-interception for most cases, but do not rely on it for private methods.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does context.proceed() do inside an @AroundInvoke method?

    proceed() continues the chain. If you do not call it, the target method does not run.
  2. 2. Two interceptors have priorities 2000 and 2100. Which is outermost?

    Lower priority values run first, so the interceptor with 2000 wraps the one with 2100.
  3. 3. What makes a decorator different from an interceptor?

    A decorator implements the interface it decorates and receives the real bean as @Delegate.
  4. 4. What is a stereotype?

    A stereotype lets you apply a recurring set of annotations with one name.
  5. 5. Why does an interceptor need @Priority in Quarkus?

    @Priority enables the interceptor globally and defines its position in the chain.

Summary

  • An interceptor binding annotation plus an @Interceptor class with @AroundInvoke adds cross-cutting logic around method calls.
  • context.proceed() continues the chain; lower @Priority values are outermost.
  • Stereotypes bundle repeating annotations.
  • Decorators implement an interface and wrap a @Delegate to change business behaviour.
  • Interceptors apply to calls that go through the container, not to arbitrary internal calls.

Next: Events and Lifecycle