深入理解事務--Spring註解式事務配置注意事項

來源:互聯網
上載者:User
1. 在需要交易管理的地方加@Transactional 註解。

@Transactional 註解可以被應用於介面定義和介面方法、類定義和類的 public 方法上。 2. @Transactional 註解只能應用到 public 可見度的方法上。

 如果你在 protected、private 或者 package-visible 的方法上使用 @Transactional 註解,它也不會報錯, 但是這個被註解的方法將不會展示已配置的事務設定。 3. 注意僅僅 @Transactional 註解的出現不足於開啟事務行為,它僅僅 是一種中繼資料。必須在設定檔中使用配置元素,才真正開啟了事務行為。  詳見最下面的配置執行個體 4. 通過 元素的 "proxy-target-class" 屬性值來控制是基於介面的還是基於類的代理被建立。

如果 "proxy-target-class" 屬值被設定為 "true",那麼基於類的代理將起作用(這時需要CGLIB庫cglib.jar在CLASSPATH中)。

如果 "proxy-target-class" 屬值被設定為 "false" 或者這個屬性被省略,那麼標準的JDK基於介面的代理將起作用。 如
<!--標準的JDK基於介面的代理將起作用-->
<tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="false"/>
<!--基於類的代理將起作用 ,同時 cglib.jar必須在CLASSPATH中-->
<tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true"/>


非JTA事務(即非分散式交易), 事務配置的時候 ,交易管理員(transactionManager)需要指定dataSource屬性(非分散式交易,事務是在資料庫建立的連結上開啟。)

JTA事務(分散式交易), 事務配置的時候 ,交易管理員(transactionManager)不能指定dataSource屬性(分散式交易,是有全域事務來管理資料庫連結的)


註解@Transactional cglib與java動態代理最大區別是代理目標對象不用實現介面,那麼註解要是寫到介面方法上,要是使用cglib代理,這是註解事物就失效了,為了保持相容註解最好都寫到實作類別方法上。
5. Spring團隊建議在具體的類(或類的方法)上使用 @Transactional 註解,而不要使用在類所要實現的任何介面上。

在介面上使用 @Transactional 註解,只能當你設定了基於介面的代理時它才生效。因為註解是 不能繼承 的,這就意味著如果正在使用基於類的代理時,那麼事務的設定將不能被基於類的代理所識別,而且對象也將不會被事務代理所封裝。 6. @Transactional 的事務開啟 ,或者是基於介面的 或者是基於類的代理被建立。

所以在同一個類中一個方法調用另一個方法有事務的方法,事務是不會起作用的。

public interface PersonService {//刪除指定id的personpublic void delete(Integer personid) ;//刪除指定id的person,flagpublic void delete(Integer personid,boolean flag) ;}public class PersonServiceBean implements PersonService {private JdbcTemplate jdbcTemplate;public void delete(Integer personid){try{this.delete(personid,true)System.out.println("delete success");}catch(Exception e){System.out.println("delete failed");}}@Transactional//此時,事務根本就沒有開啟, 即資料庫會預設提交該操作,即記錄別刪除掉 public void delete(Integer personid,boolean flag){if(flag == ture){jdbcTemplate.update("delete from person where id=?", new Object[]{personid},new int[]{java.sql.Types.INTEGER});throw new RuntimeException("運行期例外");}}}public class PersonServiceBeanTest{PersonService ps = new PersonServiceBean ();ps.delete(5);}


7. Spring使用聲明式交易處理,預設情況下,如果被註解的資料庫操作方法中發生了unchecked異常,所有的資料庫操作將rollback;如果發生的異常是checked異常,預設情況下資料庫操作還是會提交的。
public interface PersonService {//刪除指定id的personpublic void delete(Integer personid) ;//擷取personpublic Person getPerson(Integer personid);}//PersonServiceBean 實現了PersonService 介面,則基於介面的還是基於類的代理 都可以實現事務@Transactional public class PersonServiceBean implements PersonService {private JdbcTemplate jdbcTemplate;//發生了unchecked異常,交易回復, @Transactionalpublic void delete(Integer personid){jdbcTemplate.update("delete from person where id=?", new Object[]{personid},new int[]{java.sql.Types.INTEGER});throw new RuntimeException("運行期例外");}}---------------------------------------------------------------------------------------------------------------------------------------------------public interface PersonService {//刪除指定id的personpublic void delete(Integer personid) throws Exception;//擷取personpublic Person getPerson(Integer personid);}@Transactionalpublic class PersonServiceBean implements PersonService {//發生了checked異常,事務不復原,即資料庫記錄仍能被刪除,//checked的例外,需要我們在外部用try/catch文法對調用該方法的地方進行包含 @Transactionalpublic void delete(Integer personid) throws Exception{jdbcTemplate.update("delete from person where id=?", new Object[]{personid},new int[]{java.sql.Types.INTEGER});throw new Exception("運行期例外");}}---------------------------------------------------------------------------------------------------------------------------------------------------但是,對於checked這種例外,預設情況下它是不會進行交易回復的,但是如果我們需要它進行交易回復,這時候可以在delete方法上通過@Transaction這個註解來修改它的行為。@Transactionalpublic class PersonServiceBean implements PersonService {@Transactional(rollbackFor=Exception.class)//rollbackFor這屬性指定了,既使你出現了checked這種例外,那麼它也會對事務進行復原public void delete(Integer personid) throws Exception{jdbcTemplate.update("delete from person where id=?", new Object[]{personid},new int[]{java.sql.Types.INTEGER});throw new Exception("運行期例外");}}



在PersonServiceBean這個業務bean裡面,有 一些事務是不需要交易管理的,好比說擷取資料的getPersons方法,getPerson方法。因為@Transactional 放在了類的上面。

此時,可以採用propagation這個事務屬性@Transactional(propagation=Propagation.NOT_SUPPORTED),

propagation這個屬性指定了事務傳播行為,我們可以指定它不支援事務,當我們這麼寫了之後,Spring容器在getPersons方法執行前就不會開啟事務.

@Transactionalpublic class PersonServiceBean implements PersonService {@Transactional(propagation=Propagation.NOT_SUPPORTED)//則此方法 就不會開啟事務了public Person getPerson(Integer personid){}}


####################################################### 混合事務配置執行個體:

<?xml version="1.0" encoding="UTF-8"?><beans xmlns:aop="http://www.springframework.org/schema/aop"xmlns="http://www.springframework.org/schema/beans" xmlns:tx="http://www.springframework.org/schema/tx"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd    http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd    http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsdhttp://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd  "><bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close" ><property name="driverClass" value="${db.driver}"></property><property name="jdbcUrl" value="${db.url}"></property><property name="user" value="${db.username}"></property><property name="password" value="${db.password}"></property><property name="acquireIncrement" value="2"></property><property name="preferredTestQuery" value="select 1 from dual"></property><!-- <property name="idleConnectionTestPeriod" value="60"></property> --><property name="initialPoolSize" value="${db.minPoolSize}"></property><property name="minPoolSize" value="${db.minPoolSize}"></property><property name="maxPoolSize" value="${db.maxPoolSize}"></property><property name="maxIdleTime" value="${db.maxIdleTime}"></property></bean><!-- Transaction manager :非JTA事務(即非分散式交易), 事務配置的時候 ,交易管理員(transactionManager)需要指定dataSource屬性(非分散式交易,事務是在資料庫建立的連結上開啟。)JTA事務(分散式交易), 事務配置的時候 ,交易管理員(transactionManager)不能指定dataSource屬性(分散式交易,是有全域事務來管理資料庫連結的)--><bean id="transactionManager"class="org.springframework.jdbc.datasource.DataSourceTransactionManager"><property name="dataSource" ref="dataSource" /></bean><!-- 使用註解annotation定義事務: 如果 "proxy-target-class" 屬值被設定為 "true",那麼基於類的代理將起作用(這時需要CGLIB庫cglib.jar在CLASSPATH中)。如果 "proxy-target-class" 屬值被設定為 "false" 或者這個屬性被省略,那麼標準的JDK基於介面的代理將起作用。-->    <tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true" />    <!-- 使用AOP transaction定義事務 --><tx:advice id="defaultTxAdvice" transaction-manager="transactionManager">   <tx:attributes>    <tx:method name="get*" propagation="REQUIRED" rollback-for="java.lang.Exception" isolation="DEFAULT" />            <tx:method name="query*" read-only="true" />            <tx:method name="search*" read-only="true" />            <tx:method name="select*" read-only="true" />            <tx:method name="find*" read-only="true" />            <tx:method name="insert*" propagation="REQUIRED" rollback-for="java.lang.Exception" isolation="DEFAULT" />            <tx:method name="save*" propagation="REQUIRED" rollback-for="java.lang.Exception" isolation="DEFAULT" />            <tx:method name="update*" propagation="REQUIRED" rollback-for="java.lang.Exception" isolation="DEFAULT" />            <tx:method name="delete*" propagation="REQUIRED" rollback-for="java.lang.Exception" isolation="DEFAULT" />            <tx:method name="create*" propagation="REQUIRED" rollback-for="java.lang.Exception" isolation="DEFAULT" />            <tx:method name="do*" propagation="REQUIRED" rollback-for="java.lang.Exception" isolation="DEFAULT" />    <tx:method name="execute*" propagation="REQUIRED" rollback-for="java.lang.Exception" isolation="DEFAULT" />    <tx:method name="*" read-only="true" propagation="REQUIRED" isolation="DEFAULT" /> </tx:attributes></tx:advice> <tx:advice id="logTxAdvice" transaction-manager="transactionManager">           <tx:attributes>              <tx:method name="get*" propagation="REQUIRED" rollback-for="java.lang.Exception" isolation="DEFAULT" />            <tx:method name="query*" read-only="true" />            <tx:method name="search*" read-only="true" />            <tx:method name="select*" read-only="true" />            <tx:method name="find*" read-only="true" />            <tx:method name="*" propagation="REQUIRES_NEW"                  rollback-for="java.lang.Exception" />           </tx:attributes>      </tx:advice> <!-- "order"參數,這個參數是用來控制aop通知的優先順序,值越小,優先順序越高 ,混合事務配置時要制定該參數。execution:使用“execution(方法運算式)”匹配方法執行within:使用“within(類型運算式)”匹配指定類型內的方法執行 --><aop:config><aop:pointcut id="defaultOperation"              expression="execution(* *..*ServiceImpl.*(..))" />          <aop:pointcut id="logServiceOperation"              expression="@within(com.homent.service.LogService+" />                        <aop:advisor advice-ref="defaultTxAdvice" order="3" pointcut-ref="defaultOperation" />          <aop:advisor advice-ref="logTxAdvice" order="2" pointcut-ref="logServiceOperation" />  </aop:config></beans>



參考博文: http://blog.sina.com.cn/s/blog_667ac0360102ebem.html

Spring 之AOP AspectJ切入點文法詳解:http://jinnianshilongnian.iteye.com/blog/1415606


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.