Analyze the holes laid by dynamic agents for Spring transactions
Preface
Instead of writing code to get a connection, close a connection, open a transaction, commit a transaction, roll back a transaction, and so on, Spring's declarative transaction allows us to easily handle transactions through a simple @ Transactional annotation. We know that Spring transactions are based on AOP and implemented with dynamic proxies, which are easy to use, but we also encounter some pits in real-world scenarios. However, we are often at a loss when we encounter a pit, which is due to the lack of understanding of the implementation mechanism of Spring transactions. Therefore, this blog will analyze the pit laid by dynamic agents for Spring transactions from the point of view of principle.
From dynamic proxy to Spring transaction UserService:
The txMethod and txMethod2 methods simulate transaction methods (equivalent to @ Transactional)
The noTxMethod method is a common method
UserServiceImpl
In Spring transactions, we often do transaction control at the Service layer.
What we want to simulate in UserServiceImpl is:
What happens when a transactional method invokes another transactional method?
What if a method without a transaction invokes a method with a transaction?
UserHandler
For simplicity, the method name is used to determine whether to open the transaction.
Obviously, both the txMethod method and the txMethod2 method "should" open the transaction.
UserTest
Next, let's talk about the results of the run:
The proxyInstance.txMethod2 () method starts the transaction, which is fine.
The proxyInstance.txMethod () method, although the txMethod2 () transaction method is called inside the transaction method txMethod (), does not open a new transaction.
The proxyInstance.noTxMethod () method, although the transactional txMethod2 () method is called inside the non-transactional method noTxMethod (), does not open the transaction.
Let's correspond to the phenomena in Spring transactions:
The above situation, to put it bluntly, is that within an Service, nested calls between transaction methods and between ordinary methods and transaction methods do not open new transactions!
What causes it?
In fact, through the above dynamic proxy code, you should be able to find:
Dynamic proxies eventually call the original object, and when the original object invokes a method, it no longer triggers the proxy!
So how to solve it?
Quite simply, we can pull out a XxxService and call the UserService.txMethod () and UserService.txMethod2 () methods internally. All in all, avoid making nested calls to transaction methods within an Service! (this scenario transaction is invalidated because of the dynamic proxy. )
It seems that the Spring transaction is so simple, but there are these ways behind it. Have you ever been cheated?