天天看點

springmvc事務的極簡配置

springmvc事務的極簡配置

 事務有兩種方式,下面介紹程式設計式事務。(aop與事務的結合,aop需要的pom.xml配置可以去網絡擷取)

1.在spring -tx.xml頭中加入命名空間 。

xmlns:tx="http://www.springframework.org/schema/tx
 
http://www.springframework.org/schema/tx 
http://www.springframework.org/schema/tx/spring-tx.xsd      

2.然後繼續加入。

<tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="insertInto" propagation="REQUIRED"
                read-only="false" rollback-for="java.lang.Exception" />
        </tx:attributes>
    </tx:advice>
    <!-- 從spring擷取事務管理器 -->
    <bean id="transactionManager"
        class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
    </bean>      

REQUIRED解釋:

如果在同一個service類中定義的兩個方法, 内層REQUIRES_NEW并不會開啟新的事務,save和update中復原都會導緻整個事務的復原 。

如果在不同的service中定義的兩個方法, 内層REQUIRES_NEW會開啟新的事務,并且二者獨立,事務復原互不影響 。

rollback-for解釋:

Spring架構的事務基礎架構代碼将預設地 隻 在抛出運作時和unchecked exceptions時才辨別事務復原。 也就是說,當抛出個 RuntimeException 或其子類例的執行個體時。(Errors 也一樣 - 預設地 - 辨別事務復原。)從事務方法中抛出的Checked exceptions将 不 被辨別進行事務復原。

3. 然後在spring-mvc.xml中添加命名空間,在之後加入Aop配置。

<!-- 開啟Aop-->
    <aop:aspectj-autoproxy></aop:aspectj-autoproxy>
    <!-- 配置切入方法-->
    <aop:config proxy-target-class="true">
        <aop:advisor advice-ref="txAdvice" pointcut="execution(* com.service.*.*(..))" />
    </aop:config>