Spring声明式事务处理
Spring声明式事务处理也主要使用了IoC,AOP思想,提供了TransactionInterceptor拦截器和常用的代理类TransactionProxyFactoryBean,可以直接对组件进行事务代理。
使用TransactionInterceptor的步骤:
(1)定义数据源,事务管理类
(2)定义事务拦截器,例如:
<ccid_nobr> </ccid_nobr>
<ccid_code><bean id = "transactionInterceptor" class="org.springframework.transaction.interceptor.TransactionInterceptor"> <property name="transactionManager"> <ref bean="transactionManager"/></property> <property name="transactionAttributeSource"> <value>com.test.UserManager.*r=PROPAGATION_REQUIRED</value> </property> </bean></ccid_code> |
(3)为组件声明一个代理类:ProxyFactoryBean
<ccid_nobr> </ccid_nobr>
<ccid_code><bean id="userManager" class="org.springframework.aop.framework.ProxyFactoryBean"> <property name="proxyInterfaces"> <value>com.test.UserManager</value> </property> <property name="interceptorNames"> <list><idref local="transactionInterceptor"/></list> </property> </bean></ccid_code> |
使用TransactionProxyFactoryBean:
<ccid_nobr> </ccid_nobr>
<ccid_code><bean id="userManager" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean"> <property name="transactionManager"> <ref bean="transactionManager"/> </property> <property name="target"><ref local="userManagerTarget"/></property> <property name="transactionAttributes"><props> <prop key="insert*">PROPAGATION_REQUIRED</prop> <prop key="update*">PROPAGATION_REQUIRED</prop> <prop key="*">PROPAGATION_REQUIRED,readOnly</prop> </props> </property></bean></ccid_code> |
TransactionProxyFactoryBean只是为组件的事务代理,如果我们要 给组件添加一些业务方面的验证等,可以使用TransactionTemplate加拦截器方式,为组件添加多个拦截器,spring AOP中提供了三类Advice,即前增强,后增强,抛出异常时的增强,可以灵活使用。