Spring2.x中的聲明性事務(使用Annotation)


java 2008-07-03 03:03:11 閱讀134 評論0  字號: 訂閱

     剛把Spring升級成最新的2.5.5版本, 最新支持Annotation,就我的經驗來說,使用Annotation來配置事務處理,無疑是最合適的應用場景,翻看下spring的文檔,發現要加上事務非常的簡單。
  

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"

     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

     xmlns:aop="http://www.springframework.org/schema/aop"

     xmlns:context="http://www.springframework.org/schema/context"

     xmlns:tx="http://www.springframework.org/schema/tx"

    

     xsi:schemaLocation="

     http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd

     http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd

     http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd

     http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd">

 

 

  <tx:annotation-driven transaction-manager="txManager" mode="proxy" proxy-target-class="true"/>

   

      <!-- a PlatformTransactionManager is still required -->

      <bean id="txManager"class="org.springframework.jdbc.datasource.DataSourceTransactionManager">

      <!-- (this dependency is defined somewhere else) -->

      <property name="dataSource" ref="dataSource"/>

      </bean>

public Class TheClass{

    public void test(){

       testTransaction();

    }

    @Transactional   

    public void testTransaction(){    

       addCount("count",5, 10000);

       if(1==1)throw new RuntimeException("");

       addCount("count",2, 10000);

    }

}
這樣即可了, 非常值得注意的是
1.proxy-target-class="true" 一定要配上這個,否則,當然被AOP過的class爲 $Proxy6,而不是theClass了,
這樣如果要使用 TheClass theClass=(TheClass)context.getBean("theClass") 的話會拋出異常:

Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'genTrigger' defined in ServletContext resource [/WEB-INF/application-context.xml]:  nested exception is java.lang.ClassCastException: $Proxy6


加上.proxy-target-class="true"後問題解決。

2. 在theClass.
testTransaction 事務處理正常, 調用增強過的方法
theClass.test 事務處理無效, 類內部調用的時候AOP增強無效,即內部調用,是沒有增強過的。 可以考慮使用AspectJ解決這個問題,不過AspectJ經過研究,發現需要改tomcat的配置和增加jar到tomcat的lib中,對環境的依賴比較嚴重,暫時覺得代價太高,不合我們的使用。
  一個比較折中的解決方案是:
    @Transactional  

    public void test(){

       testTransaction();

    }

這樣還算完美地解決了這個問題。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章