Definition
- CGLIB proxy is the subclass Spring creates at runtime to wrap your bean; it intercepts method calls and applies cross-cutting logic like transaction management before delegating to the real method.
- Self-invocation is when a method in a class calls another method in the same class using this.method() or just method(); the call goes directly to the real object, not through the proxy.
- TransactionInterceptor is the Spring component inside the proxy that reads @Transactional metadata, starts a transaction before the method, and commits or rolls back after the method returns.
- Proxy bypass is the root cause: since Java resolves this.method() to the real object (not the proxy), the TransactionInterceptor never executes for the inner call.
- Extract to another bean is the recommended fix: move the @Transactional method to a separate Spring bean so all calls go through that bean's proxy.
- Self-injection is an alternative fix where a bean injects itself; the injected reference points to the proxy, so calling self.method() goes through the proxy.
Think of the National Bank of India compliance department. Every external customer request (method call from another bean) goes through a security checkpoint (the proxy). The checkpoint verifies identity, stamps the paperwork, and logs the visit (starts a transaction). But when one compliance officer asks a colleague sitting next to them to review a document (self-invocation), the colleague just hands over the document directly. They do not walk back to the security checkpoint. The checkpoint never logs this internal handoff, so the review happens without the proper compliance stamp (no transaction).
Understanding the Concepts
What is the self-invocation problem?
The self-invocation problem occurs when a method inside a Spring bean calls another method in the same bean, and the called method has @Transactional (or @Cacheable, @Async, etc.). The annotation is ignored because the call does not go through the Spring proxy.
Spring uses CGLIB to create a subclass of your bean at runtime. This subclass (the proxy) overrides your methods and adds transaction management logic. But when you call a method within the same class, Java resolves the call to this, which is the real object, not the proxy subclass.
package com.bank.service;
import com.bank.model.Account;
import com.bank.repository.AccountRepository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.math.BigDecimal;
@Service
public class BrokenTransferService {
private final AccountRepository accountRepository;
public BrokenTransferService(AccountRepository accountRepository) {
this.accountRepository = accountRepository;
}
// NOT @Transactional
public void processTransfer(String fromAccount, String toAccount, BigDecimal amount) {
System.out.println("processTransfer called");
// This calls executeTransfer on 'this' (the real object)
// NOT through the proxy -> @Transactional is IGNORED
executeTransfer(fromAccount, toAccount, amount);
}
@Transactional
public void executeTransfer(String fromAccount, String toAccount, BigDecimal amount) {
System.out.println("executeTransfer called");
Account sender = accountRepository.findByAccountNumber(fromAccount).orElseThrow();
Account receiver = accountRepository.findByAccountNumber(toAccount).orElseThrow();
sender.setBalance(sender.getBalance().subtract(amount));
receiver.setBalance(receiver.getBalance().add(amount));
accountRepository.save(sender);
// Simulate an error after debiting sender but before crediting receiver
if (amount.compareTo(new BigDecimal("500000")) > 0) {
throw new RuntimeException("Transfer limit exceeded");
}
accountRepository.save(receiver);
System.out.println("Transfer completed: " + amount + " from " + fromAccount + " to " + toAccount);
}
}
package com.bank;
import com.bank.model.Account;
import com.bank.repository.AccountRepository;
import com.bank.service.BrokenTransferService;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import java.math.BigDecimal;
@Component
public class SelfInvocationBugDemo implements CommandLineRunner {
private final BrokenTransferService transferService;
private final AccountRepository accountRepository;
public SelfInvocationBugDemo(BrokenTransferService transferService,
AccountRepository accountRepository) {
this.transferService = transferService;
this.accountRepository = accountRepository;
}
@Override
public void run(String... args) {
accountRepository.save(new Account("SAV2001", "Priya Sharma", new BigDecimal("1000000"), "ACTIVE"));
accountRepository.save(new Account("SAV2002", "Rajesh Kumar", new BigDecimal("200000"), "ACTIVE"));
try {
// Call processTransfer -> self-invokes executeTransfer
// @Transactional is IGNORED, no rollback on exception
transferService.processTransfer("SAV2001", "SAV2002", new BigDecimal("600000"));
} catch (RuntimeException e) {
System.out.println("Exception: " + e.getMessage());
}
// Check balances: sender was debited but receiver was NOT credited
var sender = accountRepository.findByAccountNumber("SAV2001").orElseThrow();
var receiver = accountRepository.findByAccountNumber("SAV2002").orElseThrow();
System.out.println("Sender balance: " + sender.getBalance());
System.out.println("Receiver balance: " + receiver.getBalance());
System.out.println("BUG: 600000 disappeared! No rollback because @Transactional was bypassed.");
}
}
Expected output:
processTransfer called
executeTransfer called
Exception: Transfer limit exceeded
Sender balance: 400000
Receiver balance: 200000
BUG: 600000 disappeared! No rollback because @Transactional was bypassed.
Why does this happen? How does the proxy work?
When Spring creates a bean annotated with @Transactional, it generates a CGLIB proxy subclass. The proxy overrides the annotated methods and wraps them with transaction logic. External callers receive a reference to the proxy, not the real object.
When an external bean calls transferService.executeTransfer(), the call goes to the proxy, which starts a transaction, calls the real method, and commits or rolls back. But when processTransfer() (inside the real object) calls executeTransfer(), it calls this.executeTransfer(), which resolves to the real object directly. The proxy is never involved.
package com.bank;
import com.bank.service.BrokenTransferService;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
@Component
public class ProxyVsRealDemo implements CommandLineRunner {
private final BrokenTransferService transferService;
public ProxyVsRealDemo(BrokenTransferService transferService) {
this.transferService = transferService;
}
@Override
public void run(String... args) {
System.out.println("What the controller sees:");
System.out.println(" transferService class: " + transferService.getClass().getName());
System.out.println(" Is CGLIB proxy: " +
transferService.getClass().getName().contains("$$SpringCGLIB$$"));
System.out.println();
System.out.println("Call from controller -> proxy -> real method (transaction WORKS):");
System.out.println(" controller.transferService.executeTransfer()");
System.out.println(" -> CGLIB proxy intercepts");
System.out.println(" -> TransactionInterceptor starts transaction");
System.out.println(" -> real executeTransfer() runs");
System.out.println(" -> TransactionInterceptor commits or rolls back");
System.out.println();
System.out.println("Call from processTransfer -> this.executeTransfer (transaction FAILS):");
System.out.println(" processTransfer() runs on the real object");
System.out.println(" -> this.executeTransfer() = direct call to real object");
System.out.println(" -> CGLIB proxy is NEVER involved");
System.out.println(" -> TransactionInterceptor NEVER runs");
System.out.println(" -> No transaction, no rollback");
}
}
Expected output:
What the controller sees:
transferService class: com.bank.service.BrokenTransferService$$SpringCGLIB$$0
Is CGLIB proxy: true
Call from controller -> proxy -> real method (transaction WORKS):
controller.transferService.executeTransfer()
-> CGLIB proxy intercepts
-> TransactionInterceptor starts transaction
-> real executeTransfer() runs
-> TransactionInterceptor commits or rolls back
Call from processTransfer -> this.executeTransfer (transaction FAILS):
processTransfer() runs on the real object
-> this.executeTransfer() = direct call to real object
-> CGLIB proxy is NEVER involved
-> TransactionInterceptor NEVER runs
-> No transaction, no rollback
How do you fix self-invocation? (Solution 1: extract to another bean)
The cleanest and most recommended fix is to move the @Transactional method into a separate Spring bean. This way, the call always goes through the proxy.
package com.bank.service;
import com.bank.model.Account;
import com.bank.repository.AccountRepository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.math.BigDecimal;
@Service
public class TransferExecutor {
private final AccountRepository accountRepository;
public TransferExecutor(AccountRepository accountRepository) {
this.accountRepository = accountRepository;
}
@Transactional
public void executeTransfer(String fromAccount, String toAccount, BigDecimal amount) {
System.out.println("executeTransfer called (through proxy, transaction active)");
Account sender = accountRepository.findByAccountNumber(fromAccount).orElseThrow();
Account receiver = accountRepository.findByAccountNumber(toAccount).orElseThrow();
sender.setBalance(sender.getBalance().subtract(amount));
receiver.setBalance(receiver.getBalance().add(amount));
accountRepository.save(sender);
if (amount.compareTo(new BigDecimal("500000")) > 0) {
throw new RuntimeException("Transfer limit exceeded");
}
accountRepository.save(receiver);
}
}
package com.bank.service;
import org.springframework.stereotype.Service;
import java.math.BigDecimal;
@Service
public class FixedTransferService {
private final TransferExecutor transferExecutor;
public FixedTransferService(TransferExecutor transferExecutor) {
this.transferExecutor = transferExecutor;
}
public void processTransfer(String fromAccount, String toAccount, BigDecimal amount) {
System.out.println("processTransfer called");
// Calls through TransferExecutor's proxy -> @Transactional works
transferExecutor.executeTransfer(fromAccount, toAccount, amount);
}
}
Expected output (with the fix):
processTransfer called
executeTransfer called (through proxy, transaction active)
Exception: Transfer limit exceeded
Sender balance: 1000000 (rolled back!)
Receiver balance: 200000 (unchanged)
FIX WORKS: transaction rolled back, no money lost.
How do you fix self-invocation? (Solution 2: self-injection)
You can inject the bean into itself. The injected reference points to the proxy, so calling self.method() goes through the proxy.
package com.bank.service;
import com.bank.model.Account;
import com.bank.repository.AccountRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.math.BigDecimal;
@Service
public class SelfInjectTransferService {
private final AccountRepository accountRepository;
@Autowired
@Lazy
private SelfInjectTransferService self;
public SelfInjectTransferService(AccountRepository accountRepository) {
this.accountRepository = accountRepository;
}
public void processTransfer(String fromAccount, String toAccount, BigDecimal amount) {
System.out.println("processTransfer called");
System.out.println(" this class: " + this.getClass().getSimpleName());
System.out.println(" self class: " + self.getClass().getSimpleName());
// self points to the PROXY, so @Transactional works
self.executeTransfer(fromAccount, toAccount, amount);
}
@Transactional
public void executeTransfer(String fromAccount, String toAccount, BigDecimal amount) {
System.out.println("executeTransfer called (via self-injection, transaction active)");
Account sender = accountRepository.findByAccountNumber(fromAccount).orElseThrow();
Account receiver = accountRepository.findByAccountNumber(toAccount).orElseThrow();
sender.setBalance(sender.getBalance().subtract(amount));
receiver.setBalance(receiver.getBalance().add(amount));
accountRepository.save(sender);
accountRepository.save(receiver);
}
}
Expected output:
processTransfer called
this class: SelfInjectTransferService
self class: SelfInjectTransferService$$SpringCGLIB$$0
executeTransfer called (via self-injection, transaction active)
How do you fix self-invocation? (Solution 3: ApplicationContext lookup)
You can look up the bean from the ApplicationContext. The context returns the proxy, not the real object.
package com.bank.service;
import com.bank.model.Account;
import com.bank.repository.AccountRepository;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.math.BigDecimal;
@Service
public class ContextLookupTransferService {
private final AccountRepository accountRepository;
private final ApplicationContext applicationContext;
public ContextLookupTransferService(AccountRepository accountRepository,
ApplicationContext applicationContext) {
this.accountRepository = accountRepository;
this.applicationContext = applicationContext;
}
public void processTransfer(String fromAccount, String toAccount, BigDecimal amount) {
System.out.println("processTransfer called");
// Get the proxy from the application context
var proxy = applicationContext.getBean(ContextLookupTransferService.class);
System.out.println(" proxy class: " + proxy.getClass().getSimpleName());
proxy.executeTransfer(fromAccount, toAccount, amount);
}
@Transactional
public void executeTransfer(String fromAccount, String toAccount, BigDecimal amount) {
System.out.println("executeTransfer called (via context lookup, transaction active)");
Account sender = accountRepository.findByAccountNumber(fromAccount).orElseThrow();
Account receiver = accountRepository.findByAccountNumber(toAccount).orElseThrow();
sender.setBalance(sender.getBalance().subtract(amount));
receiver.setBalance(receiver.getBalance().add(amount));
accountRepository.save(sender);
accountRepository.save(receiver);
}
}
Expected output:
processTransfer called
proxy class: ContextLookupTransferService$$SpringCGLIB$$0
executeTransfer called (via context lookup, transaction active)
What is the difference between the three solutions?
| Solution | Pros | Cons |
|---|---|---|
| Extract to another bean | Clean separation, easy to test | Adds a new class |
| Self-injection (@Lazy) | Keeps logic in one class | Circular dependency (needs @Lazy), less obvious |
| ApplicationContext lookup | No circular dependency | Couples code to Spring API, harder to test |
| AspectJ weaving | Works on private methods too | Complex build setup, slower compilation |
package com.bank;
public class SolutionComparison {
public static void main(String[] args) {
System.out.println("Self-invocation fix comparison:");
System.out.println();
System.out.println("1. Extract to another bean (RECOMMENDED)");
System.out.println(" Pro: clean design, testable, no Spring API coupling");
System.out.println(" Con: one extra class");
System.out.println();
System.out.println("2. Self-injection with @Lazy");
System.out.println(" Pro: single class");
System.out.println(" Con: circular dependency needs @Lazy, confusing for new developers");
System.out.println();
System.out.println("3. ApplicationContext lookup");
System.out.println(" Pro: no circular dependency");
System.out.println(" Con: direct Spring API usage, harder to unit test");
System.out.println();
System.out.println("4. AspectJ weaving");
System.out.println(" Pro: works on private methods, no proxy limitation");
System.out.println(" Con: complex Maven/Gradle config, slower builds");
}
}
Expected output:
Self-invocation fix comparison:
1. Extract to another bean (RECOMMENDED)
Pro: clean design, testable, no Spring API coupling
Con: one extra class
2. Self-injection with @Lazy
Pro: single class
Con: circular dependency needs @Lazy, confusing for new developers
3. ApplicationContext lookup
Pro: no circular dependency
Con: direct Spring API usage, harder to unit test
4. AspectJ weaving
Pro: works on private methods, no proxy limitation
Con: complex Maven/Gradle config, slower builds
What is a complete banking project demonstrating the bug and the fix?
Project structure
transfer-service/
├── pom.xml
└── src/
├── main/
│ ├── java/
│ │ └── com/
│ │ └── bank/
│ │ ├── TransferApp.java
│ │ ├── model/
│ │ │ └── Account.java
│ │ ├── repository/
│ │ │ └── AccountRepository.java
│ │ └── service/
│ │ ├── BrokenTransferService.java
│ │ ├── TransferExecutor.java
│ │ └── FixedTransferService.java
│ └── resources/
│ └── application.properties
└── test/
└── java/
└── com/
└── bank/
└── service/
└── TransferServiceTest.java
pom.xml
<?xml version="1.0" encoding="UTF-8"?syn-kw">>
syn-kw"><project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd"syn-kw">>
syn-kw"><modelVersionsyn-kw">>4.0.0syn-kw"></modelVersionsyn-kw">>
syn-kw"><parentsyn-kw">>
syn-kw"><groupIdsyn-kw">>org.springframework.bootsyn-kw"></groupIdsyn-kw">>
syn-kw"><artifactIdsyn-kw">>spring-boot-starter-parentsyn-kw"></artifactIdsyn-kw">>
syn-kw"><versionsyn-kw">>3.4.7syn-kw"></versionsyn-kw">>
syn-kw"></parentsyn-kw">>
syn-kw"><groupIdsyn-kw">>com.banksyn-kw"></groupIdsyn-kw">>
syn-kw"><artifactIdsyn-kw">>transfer-servicesyn-kw"></artifactIdsyn-kw">>
syn-kw"><versionsyn-kw">>1.0.0syn-kw"></versionsyn-kw">>
syn-kw"><propertiessyn-kw">>
syn-kw"><java.versionsyn-kw">>25syn-kw"></java.versionsyn-kw">>
syn-kw"></propertiessyn-kw">>
syn-kw"><dependenciessyn-kw">>
syn-kw"><dependencysyn-kw">>
syn-kw"><groupIdsyn-kw">>org.springframework.bootsyn-kw"></groupIdsyn-kw">>
syn-kw"><artifactIdsyn-kw">>spring-boot-starter-data-jpasyn-kw"></artifactIdsyn-kw">>
syn-kw"></dependencysyn-kw">>
syn-kw"><dependencysyn-kw">>
syn-kw"><groupIdsyn-kw">>com.h2databasesyn-kw"></groupIdsyn-kw">>
syn-kw"><artifactIdsyn-kw">>h2syn-kw"></artifactIdsyn-kw">>
syn-kw"><scopesyn-kw">>runtimesyn-kw"></scopesyn-kw">>
syn-kw"></dependencysyn-kw">>
syn-kw"><dependencysyn-kw">>
syn-kw"><groupIdsyn-kw">>org.springframework.bootsyn-kw"></groupIdsyn-kw">>
syn-kw"><artifactIdsyn-kw">>spring-boot-starter-testsyn-kw"></artifactIdsyn-kw">>
syn-kw"><scopesyn-kw">>testsyn-kw"></scopesyn-kw">>
syn-kw"></dependencysyn-kw">>
syn-kw"></dependenciessyn-kw">>
syn-kw"></projectsyn-kw">>
TransferServiceTest.java
package com.bank.service;
import com.bank.model.Account;
import com.bank.repository.AccountRepository;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.math.BigDecimal;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
@SpringBootTest
class TransferServiceTest {
@Autowired private BrokenTransferService brokenService;
@Autowired private FixedTransferService fixedService;
@Autowired private AccountRepository accountRepository;
@BeforeEach
void setUp() {
accountRepository.deleteAll();
accountRepository.save(new Account("SAV2001", "Priya Sharma", new BigDecimal("1000000"), "ACTIVE"));
accountRepository.save(new Account("SAV2002", "Rajesh Kumar", new BigDecimal("200000"), "ACTIVE"));
}
@Test
void brokenService_doesNotRollback() {
assertThrows(RuntimeException.class, () ->
brokenService.processTransfer("SAV2001", "SAV2002", new BigDecimal("600000")));
var sender = accountRepository.findByAccountNumber("SAV2001").orElseThrow();
// BUG: sender was debited but exception prevented crediting receiver
assertEquals(new BigDecimal("400000"), sender.getBalance());
System.out.println("BROKEN: sender balance = " + sender.getBalance() + " (money lost!)");
}
@Test
void fixedService_rollsBackCorrectly() {
assertThrows(RuntimeException.class, () ->
fixedService.processTransfer("SAV2001", "SAV2002", new BigDecimal("600000")));
var sender = accountRepository.findByAccountNumber("SAV2001").orElseThrow();
assertEquals(new BigDecimal("1000000"), sender.getBalance());
System.out.println("FIXED: sender balance = " + sender.getBalance() + " (rolled back!)");
}
}
Expected output:
[INFO] Tests run: 2, Failures: 0, Errors: 0, Skipped: 0
BROKEN: sender balance = 400000 (money lost!)
FIXED: sender balance = 1000000 (rolled back!)
[INFO] BUILD SUCCESS
What are common mistakes related to self-invocation?
Wrong: assuming @Transactional works on private methods
package com.bank.service;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
public class PrivateMethodBug {
public void publicMethod() {
// Even if privateHelper were called through a proxy,
// CGLIB cannot override private methods
privateHelper();
}
// WRONG: @Transactional on a private method does nothing
@Transactional
private void privateHelper() {
System.out.println("This method has NO transaction.");
System.out.println("CGLIB proxy cannot override private methods.");
}
}
Expected output:
This method has NO transaction.
CGLIB proxy cannot override private methods.
Correct: make the method public and call through the proxy
package com.bank.service;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
public class FixedMethodVisibility {
// CORRECT: public method, can be proxied by CGLIB
@Transactional
public void transactionalHelper() {
System.out.println("This method HAS a transaction.");
System.out.println("CGLIB proxy can override public methods.");
}
}
Expected output:
This method HAS a transaction.
CGLIB proxy can override public methods.
What should a senior or principal engineer know?
At the senior level, you should be able to explain the proxy mechanism to junior developers and spot self-invocation bugs in code reviews. You should know that this limitation applies to every proxy-based annotation: @Transactional, @Cacheable, @Async, @Retryable, and custom AOP aspects.
At the principal level, think about:
- Architectural prevention: design your services so that orchestration logic and transactional logic live in separate beans. An orchestrator bean calls transactional beans, never the other way around.
- Code review rule: flag any class that has both @Transactional and non-transactional public methods, because there is a high risk of self-invocation if one calls the other.
- AspectJ weaving trade-off: AspectJ compile-time weaving eliminates the proxy limitation entirely. Every annotated method gets the aspect applied at the bytecode level, including private methods and self-invocations. The trade-off is a more complex build pipeline and slower compilation.
- Testing strategy: write integration tests that verify rollback behavior. A test that calls a method and checks the database state after an exception catches self-invocation bugs that code reviews might miss.
package com.bank;
public class ArchitecturalGuideline {
public static void main(String[] args) {
System.out.println("Service architecture to prevent self-invocation bugs:");
System.out.println();
System.out.println("Layer 1: Controller (no @Transactional)");
System.out.println(" -> calls orchestrator");
System.out.println();
System.out.println("Layer 2: Orchestrator Service (no @Transactional)");
System.out.println(" -> validates input");
System.out.println(" -> calls external APIs");
System.out.println(" -> calls transactional service");
System.out.println();
System.out.println("Layer 3: Transactional Service (@Transactional)");
System.out.println(" -> only database operations");
System.out.println(" -> short-lived transactions");
System.out.println(" -> no HTTP calls, no file I/O");
System.out.println();
System.out.println("Layer 4: Repository (Spring Data JPA proxy)");
System.out.println(" -> auto-generated by Spring");
System.out.println();
System.out.println("Self-invocation is impossible because each layer only calls the layer below.");
}
}
Expected output:
Service architecture to prevent self-invocation bugs:
Layer 1: Controller (no @Transactional)
-> calls orchestrator
Layer 2: Orchestrator Service (no @Transactional)
-> validates input
-> calls external APIs
-> calls transactional service
Layer 3: Transactional Service (@Transactional)
-> only database operations
-> short-lived transactions
-> no HTTP calls, no file I/O
Layer 4: Repository (Spring Data JPA proxy)
-> auto-generated by Spring
Self-invocation is impossible because each layer only calls the layer below.
What are common interview follow-up questions?
- Does this problem exist with JDK dynamic proxies or only CGLIB? (It exists with both. JDK dynamic proxies use interfaces, and CGLIB uses subclasses. In both cases, self-invocation calls the real object, not the proxy.)
- Does @Transactional(propagation = REQUIRES_NEW) work with self-invocation? (No. The propagation attribute is processed by the TransactionInterceptor inside the proxy. If the call bypasses the proxy, the propagation setting is ignored.)
- Can Spring detect self-invocation at startup? (No. Spring cannot statically analyze method call graphs at startup. This is a runtime behavior.)
- Does this problem exist in other frameworks like Jakarta EE? (In Jakarta EE with EJB, container-managed transactions use a different interception mechanism that supports self-invocation. Spring chose proxy-based AOP for simplicity, which has this limitation.)
- Why does Spring not use AspectJ by default? (AspectJ requires a compile-time or load-time weaver, which adds complexity to the build. Proxy-based AOP works without any build changes and covers the majority of use cases.)
Visual Overview
Self-Invocation Proxy Bypass
=============================
External call (WORKS):
┌─────────────┐ call ┌─────────────────┐ delegate ┌─────────────────┐
│ Controller │ ────────> │ CGLIB Proxy │ ──────────> │ Real Bean │
│ │ │ │ │ │
│ │ │ 1. Start TX │ │ executeTransfer()│
│ │ │ 2. Call real │ │ │
│ │ │ 3. Commit/Rollback│ │ │
└─────────────┘ └─────────────────┘ └─────────────────┘
Self-invocation (BROKEN):
┌─────────────┐ call ┌─────────────────┐ ┌─────────────────┐
│ Controller │ ────────> │ CGLIB Proxy │ ──────────> │ Real Bean │
│ │ │ │ │ │
│ │ │ processTransfer()│ │ processTransfer()│
│ │ │ (not annotated) │ │ │
└─────────────┘ └─────────────────┘ │ │ │
│ │ this. │
│ │ executeTransfer()
│ ▼ │
Proxy is │ executeTransfer()│
BYPASSED ─────────────────> │ (NO TRANSACTION) │
└─────────────────┘
Fixed (extract to another bean):
┌─────────────┐ call ┌─────────────────┐ ┌─────────────────┐
│ Controller │ ────────> │ TransferService │ │ TransferExecutor │
│ │ │ (proxy) │ │ (proxy) │
│ │ │ │ call │ │
│ │ │ processTransfer()│ ──────────> │ 1. Start TX │
│ │ │ │ │ 2. executeTransfer│
└─────────────┘ └─────────────────┘ │ 3. Commit/Rollback│
└─────────────────┘
Key Takeaway
The self-invocation problem is one of the most common Spring pitfalls, and it catches experienced developers off guard. When a method in a class calls another method in the same class, Java resolves the call to this, the real object. Spring's CGLIB proxy, which wraps your bean to add transaction management, is never involved. The @Transactional annotation on the called method is completely ignored, and the method runs without a transaction.
In our National Bank of India transfer-service, we demonstrated the bug with a money transfer. The processTransfer() method called this.executeTransfer(), which was annotated with @Transactional. When the transfer threw an exception after debiting the sender, the debit was not rolled back because there was no transaction. The money disappeared. The fix was to extract executeTransfer() into a separate TransferExecutor bean. Now processTransfer() calls transferExecutor.executeTransfer() through the proxy, and the transaction works correctly.
Three solutions exist: extract to another bean (recommended), self-injection with @Lazy, and ApplicationContext lookup. Extracting to another bean is the cleanest because it enforces good separation of concerns and is easy to test. Self-injection works but requires @Lazy to break the circular dependency and can confuse developers who are not familiar with the pattern.
At the principal level, prevent this problem architecturally by separating orchestration logic (which calls external services, validates input, and coordinates) from transactional logic (which only does database operations). When each layer only calls the layer below, self-invocation becomes structurally impossible.
Remember one sentence: self-invocation bypasses the Spring proxy, so @Transactional on the called method is ignored; the fix is always to make the call go through the proxy, either by extracting to another bean or by self-injecting.
---