spring 事務代理創建及簡化事務配置

一.
使用TransactionProxyFactoryBean創建事務代理(通常事務代理以Service層爲目標bean)
<bean id="personService" class="com.lin.personServiceImpl">
    <property name="personDao" ref="personDao"/>
</bean>
//配置hibernate的事務管理器,使用HibernateTransactionManager類,該類實現了PlatformTransactionManager接口,針對hibernate 持久化連接的特定實現
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
    <property name="sessionFactory" ref="sessionFactory"/>
</bean>
//配置personService bean的事務代理
<bean id="personServiceProxy"
        class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
            //指定事務管理器
    <property name="transactionManager" 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" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <property name="dataSource" ref="dataSource"/>
</bean>
//配置目標bean1,該目標bean將由Bean後處理器自動生成代理
<bean id="testbean1" class="com.lin.Testbean1Impl">
    <property name="dataSource" ref="dataSource"/>
</bean
//配置目標bean2,該目標bean將由Bean後處理器自動生成代理
<bean id="testbean2" class="com.lin.Testbean2Impl">
    <property name="dataSource" ref="dataSource"/>
</bean
//配置事務攔截器bean
<bean id="transactionInterceptor"
   class="org.springframework.transaction.interceptor.TransactionInterceptor">
        //事務攔截器需要注入一個事務管理器
      <property name="transactionManager" 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>
發佈了26 篇原創文章 · 獲贊 1 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章