Video in progress

As a platform team, when do you agree to "magic" mechanisms based on annotations and reflection (custom annotations, aspects, automatic registration)?

For repeatable, cross-cutting tasks with a clear contract: audit, metrics, tracing, permission checks. Not for "magic" that changes the business flow or makes a decision that isn't visible when you read the code: explicit code is better there.

📖 Answer

Annotations and aspects are powerful, but they're invisible when you read the code. Everyone knows @Transactional; only the author knows what's happening inside @SmartRetryWithFallback(policy="v2").

My criteria for agreeing:

  • Cross-cutting and indifferent to the business. @Audited, @Timed, tracing: they don't change what the method does, they only observe. A good candidate.
  • The contract is clear and small. The annotation has 1–3 parameters, is documented, and its behavior is tested.
  • Diagnostics. At startup, misuse stops with a clear error (for example, put on a private method, where the proxy won't work; it must not swallow that silently).
  • An escape hatch. The same thing can also be done with a programmatic API.

Red flags:

  • an annotation controls the business flow: @ApproveIfAmountLessThan(1000);
  • writing to private fields with reflection, setAccessible(true): a problem with JPMS and future JDK versions, and it needs extra configuration in a GraalVM native image;
  • "automatic discovery" through classpath scanning increases startup time and errors;
  • the self-invocation trap: aspects based on Spring proxies don't work when called from inside the class, and every new annotation brings this trap back.

The alternative: explicit composition. For example, for retry, instead of an annotation use Resilience4j's programmatic API: it's visible in the code and you can step through it in the debugger.

Supplier<Rate> call = Retry.decorateSupplier(retry, () -> client.fetchRate(code));

Compile-time generation (an annotation processor, like MapStruct) is better than reflection: errors show up at build time and you can read the generated code.