---
title: "Spring事务处理的两种方式"
author: "chorpin"
date: "2008-01-14T15:22:38Z"
tags: []
categories: ["企业架构"]
slug: "spring"
draft: false
lastmod: "2008-01-14T15:22:38Z"
id: 155665
url: "https://chorpin.iteye.com/blog/155665"
---

spring事务管理：
可以通过两种方式实现，一是用AOP来控制事务：
<!-- 配置事务管理器 -->        
        <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
                <property name="sessionFactory">
                        <ref local="sessionFactory"/>
                </property>
        </bean>
    
    <!-- 配置事务特性 -->       
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
            <tx:attributes>
                    <tx:method name="*" propagation="REQUIRED"/>
                    <!--  
                    <tx:method name="add*" propagation="REQUIRED"/>
                    <tx:method name="del*" propagation="REQUIRED"/>
                    <tx:method name="update*" propagation="REQUIRED"/>
                    <tx:method name="deploy*" propagation="REQUIRED"/>
                    <tx:method name="submit*" propagation="REQUIRED"/>
                    <tx:method name="*" read-only="true"/>
                    -->
            </tx:attributes>
    </tx:advice>
    
    <!-- 配置哪些类的方法进行事务管理 -->
    <aop:config>
            <aop:pointcut id="allManagerMethod" expression="execution (* com.bjsxt.oa.managers.*.*(..))"/>
            <aop:advisor advice-ref="txAdvice" pointcut-ref="allManagerMethod"/>
    </aop:config>  



二是用事务拦截器的方式来控制事务：
<!-- Transaction manager for a single Hibernate SessionFactory (alternative to JTA) -->
    <bean id="myTransactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
        <property name="sessionFactory">
            <ref local="mySessionFactory" />
        </property>
    </bean>
    <!-- 配置事务管理 -->
    <bean id="userService" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
        <property name="transactionManager">
            <ref local="myTransactionManager" />
        </property>
        <property name="target">
            <ref local="loginTarget" />
        </property>
        <property name="transactionAttributes">
            <props>
                <prop key="save*">PROPAGATION_REQUIRED</prop>
            </props>
        </property>
    </bean>

    <!-- OrderTarget primary business object implementation -->
    <bean id="loginTarget" class="com.test.spring.UserServiceImpl">
        <property name="userDAOIF">
            <ref local="userDAO" />
        </property>
    </bean>

    <!-- DAO object: Hibernate implementation -->
    <bean id="userDAO" class="com.test.hibernate.UserDAOImpl">
        <property name="sessionFactory">
            <ref local="mySessionFactory" />
        </property>
    </bean>