歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> spring聲明式事務管理簡述

spring聲明式事務管理簡述

日期:2017/3/1 9:09:26   编辑:Linux編程

Spring 的聲明式事務管理在底層是建立在 AOP 的基礎之上的。其本質是對方法前後進行攔截,然後在目標方法開始之前創建或者加入一個事務,在執行完目標方法之後根據執行情況提交或者回滾事務。

聲明式事務管理分為兩種:1.配置文件 2.注解

1.配置文件(聲明式事務管理)用法:

在applicationContext.xml配置文件中配置①事務管理器(事務管理者)、②事務參數(事務通知)、③AOP配置

如下:

applicationContext.xml配置文件代碼

<!-- 事務管理器(事務管理者) -->
<bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="mySessionFactory"></property>
</bean>
<!-- 事務參數(事務通知) -->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
         <!-- 指定名字為add的方法進行聲明式事務管理 (指定方法)-->
<tx:method name="add*" propagation="REQUIRED" />
<tx:method name="del*" propagation="REQUIRED" />
<tx:method name="mod*" propagation="REQUIRED" />
<tx:method name="*" propagation="REQUIRED" read-only="true" />
</tx:attributes>
</tx:advice>
  <!-- AOP的配置,(指定包) -->
<aop:config>
<aop:pointcut id="interceptorPointCuts"
expression="execution(*
news.dao.*.*(..))" />
<aop:advisor advice-ref="txAdvice" pointcut-ref="interceptorPointCuts" />
</aop:config>

注意:可以在<tx:advice>中的<tx:method>的name屬性指定要進行聲明式事務管理的方法

2.注解(聲明式事務管理)用法:

比如我們要在service類中使用事務,那麼就得先在service類上面添加@Transactional,聲明這個service類中所有方法需要事務管理。然後在applicationContext.xml配置文件中配置事務管理者即可(如下):

service類代碼

@Transactional(聲明本類所有方法需要進行事務管理)
public class NewsServiceImpl implements NewsService {

  ...

}

applicationContext.xml文件代碼

1 <!-- 事務管理器(事務管理者) -->
2 <bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
3 <property name="sessionFactory" ref="mySessionFactory"></property>
4 </bean>

總結:以上就是兩種方式使用聲明式事務管理(1.配置文件 2.注解)。兩種方式都可以實現事務管理,使用注解一步到位,為什麼我們還要學一個這麼復雜的xml文件配置來實現事務管理呢。博主在當時學習的時候同樣有這樣的疑問。在這裡我簡單解析一下這兩者如何取捨。一,xml文件配置可以實現使我們的代碼簡化,並一定程度上與代碼解耦,一旦我們的工程需要替換框架,只需改動配置,而無需改動源碼。二,使用注解可以非常直觀的理解我們的源碼,提高了可讀性,不過只建議在一個相對較小,框架固定的工程中使用。具體該使用哪種方式還得依據具體情況分析。

Spring中如何配置Hibernate事務 http://www.linuxidc.com/Linux/2013-12/93681.htm

Struts2整合Spring方法及原理 http://www.linuxidc.com/Linux/2013-12/93692.htm

基於 Spring 設計並實現 RESTful Web Services http://www.linuxidc.com/Linux/2013-10/91974.htm

Spring-3.2.4 + Quartz-2.2.0集成實例 http://www.linuxidc.com/Linux/2013-10/91524.htm

使用 Spring 進行單元測試 http://www.linuxidc.com/Linux/2013-09/89913.htm

運用Spring注解實現Netty服務器端UDP應用程序 http://www.linuxidc.com/Linux/2013-09/89780.htm

Spring 3.x 企業應用開發實戰 PDF完整高清掃描版+源代碼 http://www.linuxidc.com/Linux/2013-10/91357.htm

Spring 的詳細介紹:請點這裡
Spring 的下載地址:請點這裡

Copyright © Linux教程網 All Rights Reserved