Video in progress

What problems appear when custom annotations and AOP "magic" multiply in a team, and how do you set the boundary?

An annotation hides behavior: when you read the code, you can't see what will run, ordering and self-invocation bugs appear, and debugging and testing get harder. I keep annotations for cross-cutting, uniform and rarely changing work; business logic stays in explicit code.

📖 Answer

The typical evolution: first @Audited, which is fine. Then @RequiresFeature, @RetryOnConflict, @LockByUser, @ConvertCurrency... a year later there are 6 annotations on a method and nobody can tell you the order they run in.

These are the usual problems:

  • Invisible behavior. A new developer doesn't know that @LockByUser goes to Redis; the cause of the latency isn't visible in the code.
  • Order. Which is outside, @Transactional or @Retryable? If the retry is inside the transaction, the retry happens in the same broken transaction. Without @Order, the aspect order isn't guaranteed.
  • Self-invocation. With proxy-based AOP, this.method() bypasses the aspect: the annotation is there, but there's no effect.
  • Testing. In a unit test the aspects don't run, only with a Spring context, and the tests get slower.
  • Native/AOT: proxies and reflection need extra configuration.

How I set the boundary:

  1. An annotation is only for cross-cutting, declarative jobs: transactions, metrics, audit, security. Business rules (price calculation, currency) are ordinary method calls.
  2. Every new custom annotation gets a small ADR: what it does, in what order, and how it's tested.
  3. There should be an equivalent without the annotation: auditor.record(...) can also be called by hand. It's an escape hatch for tests and complex cases.
  4. Set the order explicitly (@Order), and check it in an integration test.
  5. Explicit code is often better:
// instead of an annotation: visible and testable
return locks.withUserLock(userId, () -> walletService.debit(userId, amount));

A helper method that takes a lambda (withUserLock, inTransaction, timed) gives you a large part of the convenience of an annotation and hides nothing. I recommend such a set of helpers to the platform team, and I limit annotations to a short, agreed list.