Senior
Задача по коду: Spring @Transactional и self-invocation (скриншот с кодом)
sobes.tech AI
Answer from AI
In Spring, the @Transactional annotation works through proxies that intercept method calls and manage transactions. During self-invocation (calling a transactional method from another method of the same class directly), the proxy does not trigger, and the transaction does not start.
This happens because the call is not through the proxy, but directly via this, and Spring cannot apply the transactional aspect.
To work around this issue, you can:
- Move the transactional method to a separate bean and call it through an injected service.
- Use AopContext.currentProxy() to get the proxy and call the method through it.
Example:
@Service
public class MyService {
@Transactional
public void transactionalMethod() {
// code within a transaction
}
public void caller() {
((MyService) AopContext.currentProxy()).transactionalMethod();
}
}
And remember to enable exposeProxy = true in the Spring configuration.