spring声明式事务管理配置方式

最近学习了一下spring事务管理,这里总结一下几种不同的配置方法,如下图:

1、通过代理实现,每个bean一个代理
	<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>

2、使用拦截器
	<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>

3、使用tx标签配置
	<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>

4、注解(需要在类或方法上添加注解@Transactional
<tx:annotation-driven transaction-manager="txManager" />


示例代码:见附件。

猜你喜欢

转载自awaken2012.iteye.com/blog/1728283