本文主要是介绍Spring2.x中的声明性事务(使用Annotation),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
java 2008-07-03 03:03:11 阅读134 评论0 字号:大中小 订阅
<?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();
}
这样还算完美地解决了这个问题。
这篇关于Spring2.x中的声明性事务(使用Annotation)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!