Senior
How does the final class affect the @Transactional operation?
sobes.tech AI
Answer from AI
The @Transactional annotation in Spring is usually implemented through proxies that intercept method calls to manage transactions.
If a class is declared as final, then Spring cannot create a proxy based on inheritance (CGLIB), as inheritance from a final class is impossible. In this case:
- If JDK dynamic proxies are used (by interfaces), then a
finalclass does not interfere, as the proxy is created based on the interface. - If class-based proxies (CGLIB) are used, then a
finalclass cannot be proxied, and@Transactionalwill not work.
Thus, a final class can prevent @Transactional from working if the proxy is created through inheritance (CGLIB). To avoid issues, either do not make the class final, or use interfaces for proxying.
Example:
@Service
@Transactional
public final class MyService {
public void doWork() { /* ... */ }
}
// In this case, a CGLIB proxy will not be created, and transactions will not work.