05 xmlns:p="http://www.springframework.org/schema/p" xmlns:aop="http://www.springframework.org/schema/aop"
06 xmlns:tx="http://www.springframework.org/schema/tx"
07 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
08 http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">
09
10 …
11 12 class="org.springframework.jdbc.datasource.DataSourceTransactionManager" 13 p:dataSource-ref="dataSource"/> 14 15 16 17 18 expression="within(com.baobaotao.nestcall.BaseService+)"/> 19 20 21 22 23 24 25 26
将日志级别设置为DEBUG,启动Spring容器并执行UserService#logon()的方法,仔细观察如下输出日志:
引用
before userService.logon method...
//①创建了一个事务
Creating new transaction with name [com.baobaotao.nestcall.UserService.logon]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT
Acquired Connection [jdbc:mysql://localhost:3306/sampledb, UserName=root@localhost , MySQL-AB JDBC Driver] for JDBC transaction
Switching JDBC Connection [jdbc:mysql://localhost:3306/sampledb, UserName=root@localhost , MySQL-AB JDBC Driver] to manual commit
before userService.updateLastLogonTime...
Executing prepared SQL update
Executing prepared SQL statement [UPDATE t_user u SET u.last_logon_time = WHERE user_name = ]
SQL update affected 1 rows
after userService.updateLastLogonTime...
before scoreService.addScore...
//③ScoreService#addScore方法加入到①处启动的事务上下文中
Participating in existing transaction
Executing prepared SQL update
Executing prepared SQL statement [UPDATE t_user u SET u.score = u.score + WHERE user_name = ]
SQL update affected 1 rows
after scoreService.addScore...
Initiating transaction commit
Committing JDBC transaction on Connection [jdbc:mysql://localhost:3306/sampledb, UserName=root@localhost , MySQL-AB JDBC Driver]
…
after userService.logon method...
从上面的输出日志中,可以清楚地看到Spring为UserService#logon()方法启动了一个新的事务,而 UserSerive#updateLastLogonTime()和UserService#logon()是在相同的类中,没有观察到有事务传播行为 的发生,其代码块好像“直接合并”到UserService#logon()中。
然而在执行到ScoreService#addScore()方法时,我们就观察到发生一个事务传播的行为:" Participating in existing transaction ",这说明ScoreService#addScore()添加到UserService#logon()的事务上下文中,两者共享同一个事务。所以最终 的结果是UserService的logon()、updateLastLogonTime()以及ScoreService的addScore都工作于 同一事务中。