Deep Dive into Spring Transaction: Source Code Walkthrough and Execution Flow
This article walks through the fundamentals of Spring's transaction management, presenting a practical example, detailed execution workflow, and step‑by‑step source‑code analysis—including bean creation, AOP proxy generation, transaction attribute retrieval, transaction start, commit, and rollback – to help developers master Spring transaction internals.
1. Project Preparation
First, set up the environment. The demo code is available at GitHub . The example uses a simple user table and a UserDao interface:
public interface UserDao {
// select * from user_test where uid = "#{uid}"
MyUser selectUserById(Integer uid);
// update user_test set uname = #{uname}, usex = #{usex} where uid = #{uid}
int updateUser(MyUser user);
}A basic test class demonstrates a successful transaction:
@Service
public class Louzai {
@Autowired
private UserDao userDao;
public void update(Integer id) {
MyUser user = new MyUser();
user.setUid(id);
user.setUname("张三-testing");
user.setUsex("女");
userDao.updateUser(user);
}
public MyUser query(Integer id) {
return userDao.selectUserById(id);
}
@Transactional(rollbackFor = Exception.class)
public void testSuccess() throws Exception {
Integer id = 1;
MyUser user = query(id);
System.out.println("原记录:" + user);
update(id);
throw new Exception("事务生效");
}
}The entry point creates the Spring context and invokes the test method:
public class SpringMyBatisTest {
public static void main(String[] args) throws Exception {
String xmlPath = "applicationContext.xml";
ApplicationContext ctx = new ClassPathXmlApplicationContext(xmlPath);
Louzai uc = (Louzai) ctx.getBean("louzai");
uc.testSuccess();
}
}2. Spring Transaction Workflow
The workflow consists of two main parts:
Post‑processing : Spring creates a BeanPostProcessor that extracts transaction‑related aspects from the target bean and stores the transaction attributes in an internal cache.
Transaction execution : At runtime Spring retrieves the cached attributes, creates and starts a transaction, executes the business method, and finally commits or rolls back the transaction.
3. Source Code Analysis
3.1 Code Entry
The bean creation starts with doGetBean(), which eventually calls createBean() and doCreateBean(). These methods initialize the bean and trigger the post‑processing step that generates the AOP proxy.
3.2 Creating the AOP Proxy
The proxy creation involves two key steps:
Collect all aspects applicable to the Louzai class.
Instantiate an AOP proxy using either CGLIB or JDK dynamic proxies.
3.2.1 Getting the Aspect List
Spring first calls findCandidateAdvisors() and then findEligibleAdvisors(). The canApply() method matches the Louzai.testSuccess() method and stores its transaction attributes in attributeCache.
3.2.2 Creating the Proxy Object
The matched aspects are used to build the proxy. The actual proxy creation logic is similar to the one described in the previous Spring AOP article.
3.3 Transaction Execution
When the proxied testSuccess() method is invoked, Spring enters invokeWithinTransaction(). The core steps are:
3.3.1 Obtaining Transaction Attributes
The method retrieves the TransactionAttribute from the cached attributes.
3.3.2 Creating the Transaction
Spring calls doGetTransaction() to obtain a DataSourceTransactionObject, then doBegin() to acquire a JDBC connection, disable auto‑commit, set isolation level, and bind the connection to the thread.
3.3.3 Executing Business Logic
The original business method is executed via the InvocationCallback. If the method completes normally, Spring proceeds to commit the transaction.
3.3.4 Rolling Back the Transaction
If an exception is thrown, Spring checks whether the exception type matches the rollback rules defined in the transaction attribute. If it matches, completeTransactionAfterThrowing() triggers a rollback.
4. Conclusion
The article first introduced a simple Spring transaction usage example, then detailed the complete execution flow, and finally dissected the source code into two logical blocks: (1) matching transaction aspects and caching attributes, and (2) retrieving attributes, creating and managing the transaction, executing business logic, and committing or rolling back accordingly.
This is the fourth article in the Spring source‑code series; readers familiar with the previous AOP analysis will find it easier to follow.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Su San Talks Tech
Su San, former staff at several leading tech companies, is a top creator on Juejin and a premium creator on CSDN, and runs the free coding practice site www.susan.net.cn.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
