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();
}
這樣還算完美地解決了這個問題。