Video in progress

Strong Middle 🧱 OOP and SOLID

If you make a Spring bean class or method `final`, why might `@Transactional` stop working?

When a class has no interface, Spring builds a subclass proxy with CGLIB. A final method can't be overridden, so the proxy passes it straight through to the real object and no transaction is opened. A final class can't be proxied at all.

📖 Answer

This is a good example of how an OOP mechanism (inheritance and overriding) is used inside a framework.

@Service
public class BillingService {
    @Transactional
    public final void charge(Long id) { ... } // NO transaction
}

Spring creates BillingService$$SpringCGLIB$$0 extends BillingService and overrides every public method, opening a transaction inside. A final method can't be overridden, so the call lands on the proxy's inherited method. Even worse: the CGLIB proxy object's own fields were never injected, so inside the final method repo can be null and you can get an NPE.

If the class is final, Spring fails at startup: "Cannot subclass final class". In Kotlin, classes are final by default, so you need the kotlin-spring (allopen) plugin.

Another case that comes from the same cause is self-invocation:

public void process(List<Long> ids) {
    ids.forEach(this::charge); // the proxy is bypassed: @Transactional doesn't work
}

this is the real object, not the proxy.

How to detect it: log TransactionSynchronizationManager.isActualTransactionActive() inside the method, or set logging.level.org.springframework.transaction=TRACE and look for the "Creating new transaction" entry.

Solutions: don't make the method final; move the transactional part into another bean; if you use a JDK proxy through an interface, the final problem goes away too, but self-invocation remains.