imgn inject API GitHub

Method Interception

The problem

Timing, auditing, retries, and transactions are the same few lines wrapped around many methods. Written by hand they are copied into every method that needs them; written with a reflective proxy they cost the zero-reflection guarantee.

How it solves it

An annotation meta-annotated @InterceptingAnnotation marks calls to route through interceptors. The processor emits a subclass of the bean that overrides each intercepted method and dispatches through a chain to super:

@InterceptingAnnotation
@Retention(RUNTIME)
@Target({ElementType.TYPE, ElementType.METHOD})
public @interface Timed {
    String value() default "";
}

The interceptor is an ordinary bean marked @Intercepts, so it is injected, scoped, and conditioned like any other:

@Singleton
@Intercepts(Timed.class)
public final class TimingInterceptor implements MethodInterceptor {

    private final Metrics metrics;

    @Inject
    public TimingInterceptor(Metrics metrics) {
        this.metrics = metrics;
    }

    @Override
    public @Nullable Object invoke(MethodInvocation invocation) throws Throwable {
        long start = System.nanoTime();
        try {
            return invocation.proceed();
        } finally {
            metrics.record(invocation.annotation().stringValue("value").orElse(invocation.methodName()),
                    System.nanoTime() - start);
        }
    }
}

The bean itself changes only by being subclassable:

public class OrderService {

    @Inject
    public OrderService(Repo repo) { ... }

    @Timed("place")
    public Order place(Cart cart) { ... }
}

Because the generated proxy is the instance the injector hands out, member injection, @PostConstruct, scoping, and destruction are unaffected, and a call from one bean method to another is intercepted too.

Placement and order

A class-level annotation sweeps every declared method that is not private, static, or final, skipping Object methods, @Provides methods, and @Inject / @PostConstruct / @PreDestroy methods. A method-level annotation applies to that method alone.

Interceptors run in source order, first listed outermost, and class-level annotations wrap method-level ones:

@Retry
public class OrderService {

    @Secured
    @Timed
    public Order place(Cart cart) { ... }
}

runs Retry → Secured → Timed → place. Declaring the same annotation at both levels replaces the class-level one in place, so a method can retune @Timed("checkout") without inheriting @Timed("") as well.

Reading and substituting arguments

MethodInvocation exposes the call site as compile-time constants — no java.lang.reflect.Method anywhere — and proceed(Object...) substitutes arguments for the rest of the chain, validating count and types:

@Override
public @Nullable Object invoke(MethodInvocation invocation) throws Throwable {
    String raw = (String) invocation.arguments().get(0);
    return invocation.proceed(raw.strip());
}

Limitations