Skip to content
javahacks.dev
Spring Framework

The Spring Self Invocation Problem With AOP Explained

The Spring self invocation problem explained: why calls inside a bean skip the proxy, how it breaks Transactional, Async and Cacheable, and the fixes.

6 min read
Summarize in AI
Flat illustration of a Spring container wiring beans together, with the Spring, JUnit5, Apache Maven, Spring Boot and OpenJDK logos.

Spring applies features such as transactions, caching, retries and security through a proxy that wraps the bean. When a method of the bean calls another method of the same bean, the call does not pass through the proxy, so none of that behaviour happens. The code compiles, the annotation is present, and nothing is applied. It is one of the most reported surprises in Spring and it has a short list of fixes. This post explains the mechanism, shows how to recognise it, and ranks the fixes. It applies to Spring Framework 7.

The failing example

java
@Service
class ReportService {

    public void generateAll(List<Long> ids) {
        for (Long id : ids) {
            generate(id);              // calls this.generate(...)
        }
    }

    @Transactional
    public void generate(Long id) {
        // writes rows
    }
}

A controller calls generateAll. The author expects each generate call to run in its own transaction. It does not: generate runs with whatever transaction generateAll has, which here is none. If the third write fails, the first two stay committed and no rollback happens. The same silent failure affects @Async, which then runs the method on the caller's thread, and @Cacheable, which then never caches.

Why it works that way

Spring does not change your class. It creates a second object, the proxy, that holds the real bean and implements the same type. Callers receive the proxy, so a call from a controller goes proxy first: the proxy starts the transaction, calls the real method, then commits. Inside the real object, this refers to the real object, not to the proxy. A call to generate(id) is a plain Java method call on this, and the proxy is not involved. There is nothing to configure around this; it is how proxy-based AOP works. The proxy types and their limits are explained in Spring AOP and proxies.

How to recognise it

The symptoms depend on the annotation. For @Transactional, an exception does not roll back what was written before it, and a read-only hint is ignored. For @Async, the log line shows the caller's thread name, not a pool thread. For @Cacheable, the method body runs on every call. For @PreAuthorize, a check is skipped, which is the most dangerous case because it leaves a security rule unenforced without an error. The common reports are collected in transactions that do not apply.

A direct check is to print the class of the injected bean. A proxy shows as ReportService$$SpringCGLIB$$0, and the check AopUtils.isAopProxy(bean) returns true. If the call path goes through this, the proxy is not on it, whatever the type of the bean says.

Fix 1: move the method to another bean

java
@Service
class ReportService {

    private final ReportWriter writer;

    ReportService(ReportWriter writer) {
        this.writer = writer;
    }

    public void generateAll(List<Long> ids) {
        ids.forEach(writer::generate);      // call crosses a bean boundary, so it passes the proxy
    }
}

@Service
class ReportWriter {

    @Transactional
    public void generate(Long id) { /* ... */ }
}

This is the best fix, and it is a design improvement as well. When a method needs its own transaction, cache or retry policy, it usually has its own responsibility. Splitting it into a class says so and removes the problem without any trick.

Fix 2: put the annotation on the entry point

If the caller really wants one transaction for the whole loop, annotate generateAll instead. The calls to generate then run inside it, and you get one transaction, which may be what was intended in the first place. Think about which behaviour you want: one transaction for all, or one per item. The answer changes the correct fix.

Fix 3: inject the proxy

java
@Service
class ReportService {

    @Lazy
    @Autowired
    private ReportService self;

    public void generateAll(List<Long> ids) {
        ids.forEach(self::generate);        // goes through the proxy
    }
}

The bean receives a reference to its own proxy and calls through it. It works, it is a workaround, and it reads strangely: a class that knows it is being proxied. The @Lazy is needed to avoid a circular dependency at startup. Use it when splitting the class is not possible, for example in legacy code you may not restructure. A variant is AopContext.currentProxy(), which needs @EnableAspectJAutoProxy(exposeProxy = true) and ties the code to Spring AOP even more tightly.

Fix 4: AspectJ weaving

AspectJ changes the bytecode of the class itself, at compile time or at load time, so the advice is part of the method and self-invocation works. Enable it with @EnableTransactionManagement(mode = AdviceMode.ASPECTJ) and the AspectJ weaver. It is the complete solution, and it adds a build step and a runtime agent that most projects would rather avoid. The comparison and the cost are in Spring AOP versus AspectJ.

The proxy cannot intercept what it cannot override. A private method is never advised. A final method or a final class cannot be overridden by a class-based proxy, so advice on it is skipped, and Spring logs a warning or fails at startup depending on the case. A method called from the constructor or from @PostConstruct runs before the proxy exists. Spring 6 and later let class-based proxies advise protected and package-visible methods, but public methods remain the safe choice, and they are the only ones interface-based proxies see.

A rule for code review

Add one question to your review checklist: when a method with an AOP annotation is called, who calls it? If the caller is in the same class, the annotation does nothing. This catches most occurrences in seconds, because the pattern is visible in the diff: an annotated method, and another method in the same file calling it by name. Reviewers who have been bitten once spot it immediately. Add the case to the team's onboarding notes, with the two-line explanation that proxies wrap the bean, not the method.

Static analysis helps a little. Some IDEs flag a call from within a class to its own @Transactional method with a warning, and it is worth keeping that inspection switched on. Do not rely on it, since the inspection cannot see calls made through a method reference or a lambda in the same class.

What changes with interface-based proxies

If the bean implements an interface and Spring is configured to use JDK proxies, the proxy implements only the interface methods. A call to a method that exists on the class but not on the interface cannot go through the proxy at all, because the caller holds the interface type. Spring Boot defaults to class-based proxies, so most applications never see this, but legacy configuration with proxyTargetClass=false brings it back. When advice fails on a method that is clearly public, check which kind of proxy is in use.

Check it in a test

java
@Test
void generateAllRollsBackEachItem() {
    assertThatThrownBy(() -> reportService.generateAll(List.of(1L, 2L, -1L)))
            .isInstanceOf(IllegalArgumentException.class);

    assertThat(reportRepository.count()).isEqualTo(2);   // 1 and 2 committed, -1 rolled back alone
}

A test that asserts on the database after a failure catches a missing proxy immediately. Without it, the bug appears the first time production data contains a bad row. The transaction rules themselves are in transaction management explained, and the official text on proxying is in the Spring AOP chapter on proxying mechanisms. The reference for the transaction side is the data access chapter.

Taggedexplainer
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.