Skip to the page

Spring Boot core · mid

Proxies, @Transactional and AOP

Annotations such as @Transactional work through a proxy. A call from inside the same class skips the proxy, so the annotation does nothing.

The notes

What you must know

  • @Transactional works through a proxy around the bean. A call that comes through the proxy gets a transaction. this.saveOrder(...) inside the same class does not.
  • The same happens to @Async, @Cacheable, @Retryable, @PreAuthorize and every other proxy-based annotation.
  • Fixes: put the annotation on the method that is called from outside, move the method into another bean, or use TransactionTemplate.
  • Spring Boot uses class-based (CGLIB) proxies by default. Private methods, final methods and final classes cannot be intercepted.
  • Check: logging.level.org.springframework.transaction=DEBUG shows "Creating new transaction" when one starts.
  • Custom aspect: @Target(METHOD) @Retention(RUNTIME) @interface LogTime, then an @Aspect @Component class with @Around("@annotation(com.shop.LogTime)") and a ProceedingJoinPoint. Runtime retention is required.
  • Words: a join point is one method execution; a pointcut selects them; advice is the code that runs around them.
  • An aspect does not work for calls inside the same class, private or final methods, objects made with new, or anything that is not a bean. @Order on the aspect decides the order; the lower value runs outside. Today @Observed or @Timed from Micrometer gives timing without custom code.

The red pen

Common traps: mistake → fix

  • Mistake: @Transactional works on any method

    Fix: only on calls that come through the proxy.

  • Mistake: Making the method public fixes self-invocation

    Fix: the call still bypasses the proxy.

  • Mistake: @Async on a method called in the same class runs in the background

    Fix: it runs synchronously.

Easy to hard

Questions interviewers ask, easy to hard

  1. Why does the order row stay when saving an item fails?
  2. Which other annotations break on self-invocation?
  3. Write an aspect that logs the time of methods marked @LogTime.
  4. How do you check that a transaction really started?

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview