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();

    }

这样还算完美地解决了这个问题。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值