spring事物配置示例

来源:互联网 发布:mac怎么设置wifi热点 编辑:程序博客网 时间:2024/05/21 08:37

      以前项目中经常用spring,事务处理还没有亲自配置过, 惭愧。现在马上上路.

首先,在spring容器中,配置transactionManager,这个有好多实现,这里以HibernateTransactionManager为例,

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

然后,再定义一个事务模板

    <bean id="txProxyTemplate" abstract="true" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
        
<property name="transactionManager">
            
<ref bean="transactionManager" />
        
</property>
        
<property name="transactionAttributes">
            
<props>
                
<prop key="save*">PROPAGATION_REQUIRED,-Exception</prop>
                
<prop key="remove*">PROPAGATION_REQUIRED,-Exception</prop>
                
<prop key="update*">PROPAGATION_REQUIRED,-Exception</prop>
                
<prop key="incress*">PROPAGATION_REQUIRED,-Exception</prop>
                
<prop key="*">PROPAGATION_REQUIRED</prop>
            
</props>
        
</property>
    
</bean>

这个模板怎样应用到业务方法上呢?请看下面的配置

    <!-- 
        <bean id="userService" class="com.sclsch.service.impl.UserServiceImpl">
        <property name="userDao">
        <ref bean="BmUserDAO" />
        </property>
        </bean>
    
-->
    
<!-- 为userService配置事务-->
    
<bean id="userService" parent="txProxyTemplate">
        
<property name="target">
            
<bean class="com.sclsch.service.impl.UserServiceImpl">
                
<property name="userDao">
                    
<ref bean="BmUserDAO" />
                
</property>
            
</bean>
        
</property>
    
</bean>

注释部分是原来没有配置事务的service. parent指定为这个service配置的事务模板.