###方式一:使用註解spring
<!-- 配置事務管理器 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"></property> </bean> <!-- 使事務註解生效 --> <tx:annotation-driven transaction-manager="transactionManager"/>
備註:這種方式是,在須要加事務的方法上面使用@Transactional()來指定事務。
###方法二:使用xml配置數據庫
####配置聲明式事務流程
1.配置數據源
2.配置事務管理器,即該事務配置上面的數據源上
3.配置事務的屬性(即傳播特性),該屬性添加到上述的事務管理器上
4.配置切面
4.1 定義切點,即事務添加到哪些類上
4.2 通知:鏈接事務屬性和切點express
<!-- 配置事務管理器 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"></property> </bean> <!-- 配置事務屬性 --> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <!-- 定義查詢方法只讀 --> <tx:method name="query*" read-only="true"/> <tx:method name="find*" read-only="true"/> <tx:method name="get*" read-only="true"/> <!-- 主數據庫操做 --> <tx:method name="save*" propagation="REQUIRED"/> <tx:method name="update*" propagation="REQUIRED"/> <tx:method name="delete*" propagation="REQUIRED"/> <!-- 其它方法使用默認事務策略 --> <tx:method name="*"/> </tx:attributes> </tx:advice> <!-- 配置切面 --> <aop:config> <!-- 定義切面,全部的service的全部的方法 --> <aop:pointcut expression="execution(* com.test.spring.service.*.*(..))" id="txPointcut"/> <!-- 添加事務到切面上 --> <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut"/> </aop:config>