spring 的3种事务配置方式

本文介绍了三种Spring事务管理配置方式:使用TransactionProxyFactoryBean为每个Service配置代理;利用tx:advice与aop:config减少配置;采用注解@Transactional简化事务管理。通过对比不同配置方法的特点,帮助读者理解并选择适合项目的事务管理方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

第一种TransactionProxyFactoryBean
缺点 配置文件多,对每个service都要配置

<bean id="transactionBase" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean" lazy-init="true" abstract="true">
<property name="transactionManager" ref="transactionManager"></property>
<property name="transactionAttributes">
<props>
<prop key="add*">PROPAGATION_REQUIRED,-Exception</prop>
<prop key="update*">PROPAGATION_REQUIRED,-Exception</prop>
<prop key="insert*">PROPAGATION_REQUIRED,-Exception</prop>
<prop key="modify*">PROPAGATION_REQUIRED,-Exception</prop>
<prop key="delete*">PROPAGATION_REQUIRED,-Exception</prop>
<prop key="get*">PROPAGATION_NEVER</prop>
</props>
</property>
</bean>

<bean id="userDao" class="com.tristan.web.controller.dao.UserDAO">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>

<bean id="userManagerBase" class="com.tristan.web.controller.service.UserManager">
<property name="userDao" ref="userDao"></property>
</bean>

<bean id="userManager" parent="transactionBase">
<property name="target" ref="userManagerBase"></property>
</bean>


第二种 tx:advice + aop:config
极大的减少了配置文件

<tx:advice id="txAdvice" transaction-manager="txManager">
<tx:attributes>
<tx:method name="delete" propagation="REQUIRED" />
<tx:method name="update" propagation="REQUIRED" />
<tx:method name="*" read-only="true" />
</tx:attributes>
</tx:advice>

<aop:config>
<aop:pointcut expression="execution (* com.tristan.web.service.*.*(..))"
id="services" />
<aop:advisor advice-ref="txAdvice" pointcut-ref="services" />
</aop:config>

<context:component-scan base-package="com.tristan.web.service" />
<context:component-scan base-package="com.tristan.web.dao" />


第三种 Annotation
和上面一样都是最好的选择

<tx:annotation-driven transaction-manager="txManager" proxy-target-class="true"/>
<context:component-scan base-package="com.tristan.web.service" />
<context:component-scan base-package="com.tristan.web.dao" />


@Transactional
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值