小结:用Spring AOP配置事务要注意的几项

Spring AOP形式管理事务,Spring的官方文档写得不全,容易漏配,特总结如下:
1,数据源要加上数据源事务代理

<!-- 默认的数据源配置 -->
<bean id="talent.defaultDataSourceTarget"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<!-- org.apache.commons.dbcp.BasicDataSource -->
<!-- org.springframework.jdbc.datasource.DriverManagerDataSource -->
<property name="driverClassName"
value="${jdbc.default.driverClassName}"/>
<property name="url" value="${jdbc.default.url}"/>
<property name="username" value="${jdbc.default.username}"/>
<property name="password" value="${jdbc.default.password}"/>
</bean>
<!-- 数据源代理 -->
<bean id="talent.defaultDataSource" class="org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy">
<constructor-arg>
<ref bean="talent.defaultDataSourceTarget" />
</constructor-arg>
</bean>

2,事务特性配置时,要注明rollback-for类型,并不是所有的异常都回滚的

<!-- 配置事务特性 -->
<tx:advice id="serviceAdvice"
transaction-manager="talent.defaultTransactionManager">
<tx:attributes>
<tx:method name="add*" propagation="REQUIRED" rollback-for="Throwable"/>
<tx:method name="save*" propagation="REQUIRED" rollback-for="Throwable"/>
<tx:method name="insert*" propagation="REQUIRED" rollback-for="Throwable"/>
<tx:method name="del*" propagation="REQUIRED" rollback-for="Throwable"/>
<tx:method name="update*" propagation="REQUIRED" rollback-for="Throwable"/>
<tx:method name="*" read-only="true"/>
</tx:attributes>
</tx:advice>

3,配置哪些类的方法需要进行事务管理时,表达式要写对

<!-- 配置哪些类的方法需要进行事务管理 -->
<aop:config proxy-target-class="true">
<aop:pointcut id="servicePointcut" expression="execution(* com.jstrd.talent.manager.*.*(..))"/>
<aop:advisor pointcut-ref="servicePointcut" advice-ref="serviceAdvice"/>
</aop:config>

此处只对com.jstrd.talent.manager包下的类进行管理,并不会对其子包也进行管理的
4,要通过ctx.getBean("beanName")的形式来获取管理类,而不是new一个管理类出来
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值