第一步:在 spring的数据源配置文件(Spring-ds.xml)中配置JDBC的事务管理器
<!-- 配置事务管理器(JDBC) -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager" ></bean>
第二步:配置事务的传播特性
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="save*" propagation="REQUIRED" />
<tx:method name="add*" propagation="REQUIRED" />
<tx:method name="update*" propagation="REQUIRED" />
<tx:method name="delete*" propagation="REQUIRED" />
<tx:method name="reserve*" propagation="REQUIRED" />
<tx:method name="*" read-only="true" />
</tx:attributes>
</tx:advice>
第三步:配置事务参与的类
<!-- 通过AOP配置提供事务增强,让service包下所有Bean的所有方法拥有事务 -->
<aop:config proxy-target-class="true">
<aop:pointcut id="serviceMethod"
expression="execution(* com._xxxx.ccfw.service..*(..))" />
<aop:advisor pointcut-ref="serviceMethod" advice-ref="txAdvice" />
</aop:config>
需要注意的地方:
(1) advice(建议)的命名:由于每个模块都会有自己的Advice,所以在命名上需要作出规范,初步的构想就是模块名+Advice(只是一种命名规范)。
(2) tx:attribute标签所配置的是作为事务的方法的命名类型。
如<tx:method name="save*" propagation="REQUIRED"/>
其中*为通配符,即代表以save为开头的所有方法,即表示符合此命名规则的方法作为一个事务。
propagation="REQUIRED"代表支持当前事务,如果当前没有事务,就新建一个事务。这是最常见的选择。
(3) aop:pointcut 标签配置参与事务的类,由于是在Service中进行数据库业务操作,配的应该是包含那些作为事务的方法的Service类。
expression="execution(* com._xxxx.ccfw.service..*(..))"
其中第一个*代表返回值,第二个*代表方法名,“(..)”代表方法参数。
(4) aop:advisor 标签就是把上面我们所配置的事务管理两部分属性整合起来作为整个事务管理。
网上查找的类似图解: