最近学习了一下spring事务管理,这里总结一下几种不同的配置方法,如下图:
[img]http://dl.iteye.com/upload/attachment/0076/7307/45e7a4b2-f80b-3240-a43e-fae9581df9b5.jpg[/img]
[b]1、通过代理实现,每个bean一个代理[/b]
[b]2、使用拦截器[/b]
[b]3、使用tx标签配置[/b]
[b]4、注解(需要在类或方法上添加注解[i]@Transactional[/i])[/b]
示例代码:见附件。
[img]http://dl.iteye.com/upload/attachment/0076/7307/45e7a4b2-f80b-3240-a43e-fae9581df9b5.jpg[/img]
[b]1、通过代理实现,每个bean一个代理[/b]
<bean id="userServiceProxy"
class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
<property name="proxyInterfaces">
<list>
<value>com.dreams.spring.tx.jdbc.UserService</value>
</list>
</property>
<property name="target" ref="userService" />
<property name="transactionManager" ref="txManager" />
<property name="transactionAttributes">
<props>
<!-- PROPAGATION_REQUIRED,readOnly,-MyCheckedException(其中-代表撤销,+代表提交) -->
<prop key="add*">PROPAGATION_REQUIRED</prop>
</props>
</property>
</bean>
[b]2、使用拦截器[/b]
<bean id="transactionInterceptor"
class="org.springframework.transaction.interceptor.TransactionInterceptor">
<property name="transactionManager">
<ref local="txManager" />
</property>
<property name="transactionAttributes">
<props>
<prop key="add*">PROPAGATION_REQUIRED</prop>
</props>
</property>
</bean>
<bean
class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator">
<property name="beanNames">
<list>
需要管理事务的bean,可以定义若干个
<value>userService</value>
</list>
</property>
<property name="interceptorNames">
<list>
事务通知,可以定义多个通知
<value>transactionInterceptor</value>
</list>
</property>
</bean>
[b]3、使用tx标签配置[/b]
<tx:advice id="txAdvice" transaction-manager="txManager">
<tx:attributes>
<tx:method name="add*" propagation="REQUIRED" />
<tx:method name="*" propagation="REQUIRED" />
</tx:attributes>
</tx:advice>
<aop:config>
<!-- |第一个 * —— 通配 任意返回值类型| -->
<!-- |第二个 * —— 通配 包com.evan.crm.service下的任意class| -->
<!-- |第三个 * —— 通配 包com.evan.crm.service下的任意class的任意方法| -->
<!-- |第四个 .. —— 通配 方法可以有0个或多个参数| -->
<aop:pointcut id="allPoint"
expression="execution (* com.dreams.spring.tx.jdbc.*.*(..))" />
<aop:advisor advice-ref="txAdvice" pointcut-ref="allPoint" />
</aop:config>
[b]4、注解(需要在类或方法上添加注解[i]@Transactional[/i])[/b]
<tx:annotation-driven transaction-manager="txManager" />
示例代码:见附件。