两种Spring声明式事务管理简述之二

3、基于 命名空间的声明式事务管理(以配置hibernate框架为例)
在以往的编程式事务管理中事务管理的代码嵌套在业务逻辑代码之中,包括事务的开始、提交或者回滚,这样的架构使得代码杂糅过多,不仅实现复杂,并且后期维护起来也更加困难。Spring声明式事务管理在底层采用了AOP技术,即将事务管理作为一个“方面”代码单独编写,程序员只需要关心业务逻辑代码的实现,然后通过AOP技术将事务管理的“方面”代码织入到业务类中,使得代码分工明确,后期的维护也更加简单。
基于 命名空间的声明式事务管理首先需要在applicationContext.xml文件中增加事务管理所需的常用命名空间声明,如下:

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
    xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="    
            http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd  
            http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd  
            http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd
            http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.2.xsd  
            http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.2.xsd">

接着在配置文件中声明TransactionManager,并且设置sessionFactory属性。

<bean id="transactionManager"class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFacatory" ref="sessionFactory>
</property>
</bean>

定义事务通知,指定之前定义的TransactionManager,并且在其属性中声明事务规则。

<--定义事务通知-->
<tx:advice id="bankAdvice" transaction-manager="transactionManager">
<--指定事务传播规则-->
<tx:attributes>
<--对方法transfer应用REQUIRED事务传播规则-->
<tx:method name="transfer" propagation="REQUIRED"/>
</tx:attributes>
</tx:advice>

接着定义一个切面,将事务通知与切面进行组合。

<--定义切面,并将切面与通知进行组合-->
<aop:config>
<--对所有的transfer方法都应用事务规则-->
<aop:pointcut id="bankPointcut" expression="execution(* *.transfer(..))"/>
<--将事务通知和切面进行组合-->
<aop:advisor advice-ref="bankAdvice" pointcut-ref="bankPointcut"/>
</aop:config>

至此,基于 命名空间的声明式事务配置完成。
4、基于 @Transactional 的声明式事务管理
基于注解@Transactional 的声明式事务管理更加简单,在配置文件中配置完TransactionManager bean之后增加如下配置即表示引入基于 @Transactional 的声明式事务管理

<tx:annotation-driven transaction-manager="transactionManager"/>

然后在需要增加事务管理的类或者方法的前面增加如下的代码(指定了事务管理的隔离级别、传播行为)即表示使用对该方法使用事务管理。

@Transactional(propagation=Propagation.REQUIRED,isolation=Isolation.DEFAULT)

尽管基于@Transactional的声明式事务管理配置更加简单,但不足的是在应用该事务管理的每个类或方法上都必须声明一次,太麻烦,而且似乎该声明只能适用于public方法。我们在使用事务管理时应酌情考虑,看使用哪种方式更适合自己。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值