Spring Aop实现声明式事务

来源:互联网 发布:java程序是什么 编辑:程序博客网 时间:2024/06/05 09:50

在系统的业务逻辑层中,每个业务会涉及到多个数据库的操作,业务层其实是通过数据层的多个方法共同完成一个业务,而这些方法要么都执行,要么都不执行,否则会造成数据的不一致,由此我们要对业务层进行事务管理。我们有以下两种方式实现对业务的事务控制。

1.    传统的方式:

每个业务方法都手动加上事务控制的代码。

2.    采用aop的方式。(事务处理可以看做是业务的一个方面,我们采用aop的方面对这方面进行统一的处理)

下面我们采取zop的方式实现一个对业务层事务的统一处理

2.1    修改applicationContext.xml

目的是使其支持<tx> <aop>标签。

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"

    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx"

    xmlns:aop="http://www.springframework.org/schema/aop"

    xsi:schemaLocation="http://www.springframework.org/schema/beans

    http://www.springframework.org/schema/beans/spring-beans-2.5.xsd 

    http://www.springframework.org/schema/tx

    http://www.springframework.org/schema/tx/spring-tx-2.5.xsd 

    http://www.springframework.org/schema/aop

    http://www.springframework.org/schema/aop/spring-aop-2.5.xsd 

   ">

2.2    配置声明式事务

    

<!--

    spring 提供的对hibernate事务处理的类型相当于我们前面讲的logAdive,其实就是对事务进行统一管理的一个类

    -->

    <bean name="trasactionManager"

       class="org.springframework.orm.hibernate3.HibernateTransactionManager">

       <!--

       此属性值被HibernateTransactionManager管理的session工厂,

       注意sessionFactory已经在上面定义过spring整合hibernate时讲过,

       注意事务管理最终就是管理session,所以这里要这样配置

       --><property name="sessionFactory" ref="sessionFactory"></property>

    </bean>

    <!--

    定义以何种方式进行事务处理

    -->

    <tx:advice id="myadvice" transaction-manager="trasactionManager">

       <tx:attributes>

       <!--

            add开头的方法采用必要的事务处理,出错时回滚-->

            <tx:method name="add*" propagation="REQUIRED" rollback-for="Exception" />

           <tx:method name="edit*" propagation="REQUIRED"

              rollback-for="Exception" />

           <tx:method name="del*" propagation="REQUIRED" rollback-for="Exception" />

           <tx:method name="drop*" propagation="REQUIRED"

              rollback-for="Exception" />

           <tx:method name="register*" propagation="REQUIRED"

              rollback-for="Exception" />

                  <!--

            对不合以上规则的其他方法不做事务提交或回滚处理,是只读的,一般是指不涉及到数据库更新的方法-->

           <tx:method name="*" read-only="true" />

       </tx:attributes>

    </tx:advice>

    <aop:config>

    <!--

      切点:  对哪些包下面的接口进行事务管理

      第一个星号代表方法返回值类型任意。

        第二个星号代表包下面的接口或类名任意。

       第三个星号代表包下面的接口或类的方法名任意。

       小括号里的两个点代表方法参数任意   

       --><aop:pointcut expression="execution(* com.struts.service.*.*(..))"

           id="mycutpoint" /><!--

           以何种方式处理知道了,对象进行处理知道了,下面就是整合了

       --><aop:advisor advice-ref="myadvice" pointcut-ref="mycutpoint" />

    </aop:config>

原创粉丝点击