Spring之事務管理配置

1. 基於註解的事務配置

  1. 在須要添加事務的方法上加上@Transactional註解
  2. Spring的配置文件中配置事務管理器
    
 1     <!-- 添加事務管理器組件DataSourceTransactionManager -->
 2     <bean id="transactionManager"
 3  class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
 4         <!-- 使用set方法注入數據源 -->
 5         <property name="dataSource" ref="dataSource"></property>
 6     </bean>
 7 
 8     <!-- 開啓基於註解聲明式事務 注意配置transaction-manager屬性,它引用了咱們事務管理組件對象,這裏要和事務管理器組件id一致  9  默認是transactionManager -->
10     <tx:annotation-driven transaction-manager="transactionManager" />
 

2. 基於XML的事務配置

  1. 在Spring的配置文件中進行配置
  
 1     <!-- 配置事務管理器 -->
 2     <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
 3         <!-- 裝配數據源 -->
 4         <constructor-arg name="dataSource" ref="dataSource"></constructor-arg>
 5     </bean>
 6     <!--使用xml配置事務方法 -->
 7     <aop:config>
 8         <!-- 設置添加事務的方法,使用切入點表達式-->
 9         <aop:pointcut expression="execution(* *.checkout(..))" id="mypoint"/>
10         <!-- 將事務方法和事務的相關配置關聯起來 -->
11         <aop:advisor advice-ref="myAdvice" pointcut-ref="mypoint" />
12     </aop:config>
13     <!-- tx配置事務的屬性 (使用tx名稱空間)-->
14     <tx:advice id="myAdvice" transaction-manager="transactionManager">
15         <tx:attributes>
16             <!-- 配置事務的屬性,多個事務方法也能夠在這個裏面放,name設置事務方法名,propagation設置事務相關信息 -->
17             <tx:method name="checkout" propagation="REQUIRED"/>
18         </tx:attributes>
19     </tx:advice>
相關文章
相關標籤/搜索