首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

spring 事宜代理创建及简化事务配置

2012-08-24 
spring 事务代理创建及简化事务配置一.使用TransactionProxyFactoryBean创建事务代理(通常事务代理以Servi

spring 事务代理创建及简化事务配置
一.
使用TransactionProxyFactoryBean创建事务代理(通常事务代理以Service层为目标bean)
<bean id="personService" ref="personDao"/>
</bean>
//配置hibernate的事务管理器,使用HibernateTransactionManager类,该类实现了PlatformTransactionManager接口,针对hibernate 持久化连接的特定实现
<bean id="transactionManager" ref="sessionFactory"/>
</bean>
//配置personService bean的事务代理
<bean id="personServiceProxy"
        ref="transactionManager"/>
            //指定需要生成代理的日标bean
    <property name="persionService" ref="persionService"/>
            //指定事务属性
    <property name="transactionAttributes"
        <props>
            <prop key="insert*">PROPAGATION_REQUIRED,-MyCheckedException</prop>
            <prop key="update*>PROPAGATION_REQUIRED</prop>
            <prop key="*">PROPAGATION_REQUIRED,readOnly</prop>
        </props>
    </property>


二.使用自动创建代理简化事务配置
   使用BeanNameAutoProxyCreator 和DefaultAdvisorAutoProxyCreator创建代理时,并不一定是创建事务代理,关键在于传入的拦截器,如果传入事务拦截器,将可自动生成事务代理.
//使用jdbc局部事务策略
<bean id="transactionManager" ref="dataSource"/>
</bean>
//配置目标bean1,该目标bean将由Bean后处理器自动生成代理
<bean id="testbean1" ref="dataSource"/>
</bean
//配置目标bean2,该目标bean将由Bean后处理器自动生成代理
<bean id="testbean2" ref="dataSource"/>
</bean
//配置事务拦截器bean
<bean id="transactionInterceptor"
   ref="transactionManager"/>
       <property name="transactionAttributes">
            //定义事务传播属性
            <props>
                    <prop key="insert*">PROPAGATION_REQUIRED</prop>
                    <prop key="find*">PROPAGATION_REQUIRED,readOnly</prop>
                    <prop key="*">PROPAGATION_REQUIRED</prop>
            </props>
        </property>
    //定义BeanNameAutoProxyCreator的Bean后处理器
<bean class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator">
    <property name="beanNames">
        <list>
            <value>testbean1</value>
            <value>testbean2</value>
        </list>
            //此处可以增加其他需要创建事务代理的bean
    </property>
        //定义BeanNameAutoProxyCreator所需要的拦截器
     <property name="interceptorNames">
        <list>
            <value>transactionInterceptor</value>
                //此处可以增加其他新的Interceptor
        </list>
    </property>
</bean>

热点排行