java / expert
Snippet
Solving @Transactional Self-Invocation with ObjectProvider
Spring's @Transactional relies on AOP proxies. Calling a transactional method directly from within the same class bypasses the proxy. Using ObjectProvider to self-inject the bean ensures the call goes through the proxy.
snippet.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
@Servicepublic class OrderService {private final ObjectProvider<OrderService> self;public OrderService(ObjectProvider<OrderService> self) {this.self = self;}public void processOrder() {// Self-invocation via proxy to ensure @Transactional is honoredself.getIfAvailable().saveToDatabase();}@Transactionalpublic void saveToDatabase() {// Database logic here}}
spring
Breakdown
1
ObjectProvider<OrderService> self
Provides a lazy-loaded reference to the proxied version of the current bean.
2
self.getIfAvailable().saveToDatabase()
Invokes the method on the proxy, triggering the transactional interceptor.