日期:2014-05-16  浏览次数:20483 次

SPRING JDBC事务管理的三种配置方法

一.???? 一般的JDBC事务,通常可以这样处理:

<bean id="txProxyTemplate" abstract="true"???
class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">???
??? <property name="transactionManager">??
??????? <ref bean="transactionManager"/>??
??? </property>???
??? <property name="transactionAttributes">???
??????? <props>??
??????????? <prop key="find*">PROPAGATION_REQUIRED, readOnly</prop>???
??????????? <prop key="*">PROPAGATION_REQUIRED</prop>???
??????? </props>???
??? </property>???
</bean>???

<bean id="userManager" parent="txProxyTemplate">???
??? <property name="target">???
??????? <bean class="some.package.UserManagerImpl">???
??????????? <property name="userDAO"><ref bean="userDAO"/></property>???
??????? </bean>???
??? </property>???
</bean>???

以后,如果增加新的Service/Manager,则XML配置的增量是这一段:

<bean id="someOtherManager" parent="txProxyTemplate" >???
??? <property name="target">???
??????? <bean class="some.package.someOtherManagerImpl">???
??????? </bean>???
??? </property>???
</bean>

?

?

?

?

二.每次都要添加这段重复的代码,有点繁琐,可以使用TransactionInterceptor进行一点简化:

?

<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
?? <property name="dataSource">
??? <ref local="dataSource" />
?? </property>
</bean>

?

<bean id="transactionInterceptor" class="org.springframework.transaction.interceptor.TransactionInterceptor">
?? <property name="transactionManager" ref="transactionManager"/>
?? <property name="transactionAttributes">
??? <props>
???? <prop key="*">PROPAGATION_REQUIRED</prop>
???? <prop key="get*">PROPAGATION_REQUIRED,readOnly</prop>
???? <prop key="find*">PROPAGATION_REQUIRED,readOnly</prop>
???? <prop key="request*">PROPAGATION_REQUIRED,readOnly</prop>
??? </props>
?? </property>
</bean>

<bean class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator">
?? <property name="beanNames">
??? <value>*Service</value>
?? </property>
?? <property name="interceptorNames">
??? <list>
???? <value>transactionInterceptor</value>
??? </list>
?? </property>
</bean>

<bean class="org.springframework.transaction.interceptor.TransactionAttributeSourceAdvisor">
?? <property name="transactionInterceptor" ref="transactionInterceptor"/>
</bean>

关键在上面的高亮处,只要类的名字满足*Service的规则,那么它就会对这个类进行事务管理!

如此,我们无需再添加累赘的代码,只要名字满足规则就ok了!

?

?

?

三.第三种 tx:advice 和 aop:config 简化配置事务:

??? <tx:advice id="txAdvice" transaction-manager="transactionManager">
??????? <tx:attributes>
??????????? <tx:method name="add*" propagation="REQUIRED" />
??????????? <tx:method name="delete*" propagation="REQUIRED" />
??????????? <tx:method name="update*" propagation="REQUIRED" />
??????????? <tx:method name="add*" propagation="REQUIRE